Ali Bahaari Ali Bahaari - 4 months ago 7
HTML Question

Parents method doesn't work for closing Two Pages

I have Two Pages that both of them has an image that is used as a Close Button. This is HTML Code :

<div id="bioPage">
<img id="closeBtn" src="Images/CloseButton.png" alt="Close Button" />
</div>
<div id="skillsPage">
<img id="closeBtn" src="Images/CloseButton.png" alt="Close Button" />
</div>


& I want to write a code just once to close pages when the Close Button in them clicked. So I wrote this :

$('#closeBtn').click(function() {
var parentDiv = $(this).parents('div:first');
parentDiv.css('left', '-100%');
$('nav').animate({
'left': '0px'
}, 500);
});


But It works for the First Page & Second Page doesn't close when the Close Button clicked.

Answer

This is expected behavior. Identifiers in HTML must be unique. You can use a common class with the elements then easily use Class Selector (“.class”)

HTML

<img class="closeBtn" src="Images/CloseButton.png" alt="Close Button" />

Script

$('.closeBtn').click(function() {
});