This is the code in my html file:
<div id="centerBlock">
<block>
<site style="padding-top: 10px; margin-left: 20px">
<img src="./images/site1.png" alt="some_text"/>
</site>
<textOnImage style="padding-top: 10px; margin-left: 20px">
lolol
</textOnImage>
</block>
<block>
<site style="padding-top: 163px; margin-left: 20px">
<img src="./images/site1.png" alt="some_text"/>
</site>
<textOnImage style="padding-top: 163px; margin-left: 20px">
lolol
</textOnImage>
</block>
</div>
And this is my javascript:
$("block").mouseenter(function(){
$("site").fadeTo("slow", 0.25);
$("textOnImage").animate({
opacity: "1"
}, 600 );
});
$("block").mouseleave(function(){
$("site").fadeTo("slow", 1);
$("textOnImage").animate({
opacity: "0"
}, 600 );
});
However, when I hover over one of the two block elements they both go down in opacity and when I move my mouse away from it than they both go back to the original state. I've searched for hours, and I'm 100% sure I've been searching the incorrect terms. How do I do them individually?
Use this to target only the block that triggered the event and then use .find() to find the desired element in that specific block. The way you were doing it before was obviously finding all site elements and all textOnImage elements in the whole page not only the ones in the block that triggered the event.
$("block").mouseenter(function(){
var $this = $(this);
$this.find("site").fadeTo("slow", 0.25);
$this.find("textOnImage").animate({
opacity: "1"
}, 600 );
});
$("block").mouseleave(function(){
var $this = $(this);
$this.find("site").fadeTo("slow", 1);
$this.find("textOnImage").animate({
opacity: "0"
}, 600 );
});
You need to traverse into the structure of the hovered element. You can use .find() like this...
$("block").mouseenter(function(){
$(this).find("site").fadeTo("slow", 0.25);
$(this).find("textOnImage").animate({
opacity: "1"
}, 600 );
});
$("block").mouseleave(function(){
$(this).find("site").fadeTo("slow", 1);
$(this).find("textOnImage").animate({
opacity: "0"
}, 600 );
});
Within an event handler, this is a reference to the element to which the handler is bound.
You could have also used .children() instead of .find() since the targeted elements are only one level deep.
Side note, you can use .hover(), and pass two functions like this..
$("block").hover(function(){
$(this).find("site").fadeTo("slow", 0.25);
$(this).find("textOnImage").animate({
opacity: "1"
}, 600 );
},
function(){
$(this).find("site").fadeTo("slow", 1);
$(this).find("textOnImage").animate({
opacity: "0"
}, 600 );
});
You'll probably also want to add some .stop() calls before your fadeTo and animate calls, otherwise when you mouse over and out rapidly, the animations will get backed up in a queue.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With