Issue
Using Event Delegation, is there a way to check the element that was fired if it has a particular attribute or specifically a class or an ID?
<ul>
<li><button>Make the first paragraph appear</button></li>
<li><button>Make the second paragraph appear</button></li>
<li><button>Make the third paragraph appear</button></li>
</ul>
<div>
<p class="first">First paragraph</p>
<p class="second">Second paragraph</p>
<p class="third">Third paragraph</p>
</div>
Let's say all the paragraphs are hidden initially and clicking on the first button, the first paragraph appears and clicking on the second button, the first paragraph is hidden and the second paragraph is displayed and when the third button is clicked, the second paragraph is hidden while keeping the first paragraph hidden as well.
My solution so far was to make a event handler for each specific button and hide the other two paragraphs while only showing one. It works but if the number of elements increased, the event handlers needed for each one would increase too. Is there a better way to do this?
Solution
If the index of buttons and paragraphs are the same then you can make use of .index():
$('button').click(function() {
var idx = $(this).index('ul li button');
$('div p').eq(idx).show().siblings('p').hide();
});
or you can use data-* attribute if the index are different:
<ul>
<li><button data-parapgraph="first">Make the first paragraph appear</button></li>
<li><button data-parapgraph="second">Make the second paragraph appear</button></li>
<li><button data-parapgraph="third">Make the third paragraph appear</button></li>
</ul>
<div>
<p class="first">First paragraph</p>
<p class="second">Second paragraph</p>
<p class="third">Third paragraph</p>
</div>
then apply .data() to retrieve the data-* attribute:
$('button').click(function() {
var parapgraph = $(this).data('parapgraph');
$('p.' + parapgraph).show().siblings('p').hide();
});
Answered By - Felix
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.