Reputation: 5
I know this is simple question but I am having trouble find a solution.. I have the following div structure..
<div id="myid">
<div id="toggle">
<img id="img" src="test_img.jpg" width="300" height="200">
</div>
</div>
<script>
$("#myid").mouseenter(function() {
$("#toggle").css("background-image", "url(test_img_b.jpg)");
$('#myid').children().animate({width: "0px", marginLeft: 0, opacity:0}, 'slow', function() {$(this).remove();});
});
</script>
The code works fine, The issue is I do not want to refer "#toggle" div by its name, I want access through a child property or something similar. Because I will be having many block of "#myid" divs, and want the "#toggle" div animate depending on which div is hovered...
I hope I made my question clear.
Thank you - Malind
Thank you all, I have changed my scope according to your suggestions below and achieved what i wanted in the first place.
Regards Malind
Upvotes: 0
Views: 134
Reputation: 388406
Id element must be unique so you can't have multiple elements with the same id - use class instead
<div class="myid">
<div class="toggle">
<img class="img" src="test_img.jpg" width="300" height="200">
</div>
</div>
then
$(".myid").mouseenter(function () {
$(this).find(".toggle").css("background-image", "url(test_img_b.jpg)");
$(this).find('.img').animate({
width: "0px",
marginLeft: 0,
opacity: 0
}, 'slow', function () {
$(this).remove();
});
});
Demo: Fiddle
Upvotes: 1
Reputation: 2972
Try this:
$("#myid div")
That refers to ALL divs inside #mydiv
but really you're approaching it wrong. you can only have one unique id, but multiple classes. so select the class, not the id.
<div class="parent" id="myid">
<div class="toggle">
<img id="img" src="test_img.jpg" width="300" height="200">
</div>
</div>
<script>
$("#myid").mouseenter(function() {
var $this = $(this);
$('.toggle', $this) //here you are setting the scope to the div you are entering
.css("background-image", "url(test_img_b.jpg)")
.animate({
width: "0px",
marginLeft: 0,
opacity:0
}, 'slow');
}), function() {
var $this = $(this);
$('.toggle', $this)
.animate({
width: "0px",
marginLeft: 0,
opacity:0
}, 'slow', function() {
$(this).remove();
});
});
</script>
you could do $('#myid').find('.toggle') but it's inefficient, and you should define your scope first, and then apply it. var $id = $('#myid'); $('.toggle', $id) and your scope can then be used over and over again without having to use .find() over and over.
Upvotes: 0