Samuel
Samuel

Reputation: 781

How to do an if not conditional test with jquery?

I have a tag that appears on an image when the mouse enters the image. When I want to go on the link with the mouse the link logically disappears because i used .mouseleave() function to hide the link when the mouse leaves the image.

I thought to do a conditional test for the .mouseleave() as follow:

if(!$("#linkId").mouseenter()){
//...
}

I tried with .not().mousenter() instead of ! not

But it does not work.. When I enter on the link, it stays and it it never leaves...

Thank you

Sam

Upvotes: 0

Views: 236

Answers (2)

Felix Kling
Felix Kling

Reputation: 816700

Put both, the link and the image in a container and assign the event handler to the container instead. You can position the link with CSS.

As the link and the image are children of the parent, the mouseleave event is not triggered when you hover over the link.

Example:

HTML:

<div id="parent">
    <div id="image"></div> <!-- the div is just an example -->
    <a id="link" href="#">Some link</a>
</div>

CSS:

#parent {
    position: relative;
}

/* used div for demo only */
#image {
    width: 100px;
    height: 100px;
    border: 1px solid black;
}

#link {
    position: absolute;
    top: 0;
    left: 0;
    display: none;
}

JavaScript:

$('#parent').hover(function() {
    $('#link').toggle();
});

DEMO


$("#linkId").mouseenter() is not doing what you think it does. It does not test whether the mouse is over the link or not, it generates a mouseenter event on the link.

Upvotes: 3

smdrager
smdrager

Reputation: 7417

Use hover(), and either bind it to both the link and the image, or have the image within the link element.

i.e.

<img src="example.gif" alt="" id="showme" style="display:none" />
<a href="#" id="hoverme">Hover me</a>

<script type="text/javascript">
    $('#hoverme,#showme').hover(function(){
        $('#showme').toggle();
    });
</script>

Upvotes: 0

Related Questions