Reputation: 111
I am having the below code and have multiple parent divs on same page.
<div class="full-width" id="edit">
<img id="edit-click" class="responsive" src="./images/icon.png">
<div id="editable" class="editable"> 1 </div>
</div>
<div class="full-width" id="edit">
<img id="edit-click" class="responsive" src="./images/icon.png">
<div id="editable" class="editable"> 2 </div>
</div>
What I want to achieve is : on clicking the image(#edit-click) the sub element (#editable) div should open up only for that particular parent div.
How can I achieve this.. ?
$('#edit').on('click', '#edit-click', function (e) {
$(this).children('#editable').fadeIn( "slow");
});
but this is not targetting the #editable div of the same parent div :(
Any help will be appreciated.
Thanks!
Upvotes: 0
Views: 71
Reputation: 24001
As I said Id must be unique (I know this is a little bit confused about id must be unique while it can works fine with css .. but you can try click event here it will just work with the first element https://jsfiddle.net/mohamedyousef1980/1vrdbzgL/ and you can take a look at Does ID have to be unique in the whole page?
so your code should be something like this
in html
<div class="full-width" id="edit1">
<img id="edit-click1" class="responsive" src="./images/icon.png">
<div id="editable1" class="editable"> 1 </div>
</div>
<div class="full-width" id="edit2">
<img id="edit-click2" class="responsive" src="./images/icon.png">
<div id="editable2" class="editable"> 2 </div>
</div>
in js you need to use .closest()
and .find()
$('.full-width').on('click', '.responsive', function (e) {
$(this).closest('.full-width').find('.editable').fadeIn( "slow");
});
Additional for fadeToggle you can use
$('.full-width').on('click', '.responsive', function (e) {
var getEditable = $(this).closest('.full-width').find('.editable');
$('.editable').not(getEditable).hide();
getEditable.fadeToggle( "slow");
});
Note: be sure you include jquery
Upvotes: 1
Reputation: 652
You better do it this way.
<div class="full-width" id="edit1">
<img class="edit-click responsive" src="http://lorempixel.com/50/50">
<div id="editable1" class="editable"> 1 </div>
</div>
<div class="full-width" id="edit2">
<img class="edit-click responsive" src="http://lorempixel.com/50/51">
<div id="editable2" class="editable"> 2 </div>
</div>
Use classes instead of IDs.
And use CSS classes instead of jQuery fadeIn, fadeOut.
.editable {
display: none;
}
.active .editable {
display: block;
}
https://jsfiddle.net/hje00xyg/
Upvotes: 0
Reputation: 25352
Id must be unique insetad take class as selector
Like this
$(".full-width").on("click", ".responsive", function() {
$(this).siblings(".editable").fadeIn("slow");
})
Upvotes: 1