Show hide content when clicked on a specific id

Asked

Viewed 47 times

2

Let’s assume I have two links

<a href="#pessoa1">link1</a>
<a href="#pessoa2">link2</a>

The content shown will only refer to the link clicked and when you click on another link the content currently open will be closed

<div id="pessoa1"></div>
<div id="pessoa2"></div>

Code in jquery I tried to use [id ="person"] to pick up content by number but it doesn’t work, some hint?

<script>
$('a').click(function(e){
    $('[id^="pessoa"]').show("slow");
    e.preventDefault();
    return false;
});
</script>

1 answer

2


It would be like this, taking the href of the clicked element, which is the id of their div:

$('a').click(function(e){
   $("div[id^='pessoa']").hide();
   var id = $(this).attr("href");
    $(id).show("slow");
    e.preventDefault();
});
div[id^='pessoa']{
   display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#pessoa1">link1</a>
<a href="#pessoa2">link2</a>
<br>
<div id="pessoa1">p1</div>
<div id="pessoa2">p2</div>

The return false; is not necessary.

  • Cool, I just don’t understand one thing, does [id ='person'] work like this in css? Something else like closing open content when you click another?

  • Yes, it works in CSS. It will hide the ids that start with "person".... I will change the answer to hide the other.

  • To be more specific, you can do div[id^='pessoa']

  • @user4451 Updated answer. You can use the same selector in jQuery to hide the Divs.

  • Gosh, that dough, thank you, I was almost getting it but only lacked a thing or other in the code hehehe!!!

  • @user4451 Now this return false; no need. You can remove.

  • If the answer solved, be sure to mark . =] Thanks!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.