Maja Jelen
Maja Jelen

Reputation: 223

Mouseover problems and jquery issue

I have a problem with jquery effects on few blocks. Mouseenter and mouseleave work only on the first div block while on all others it doesn't.

Here is the JS:

 $(document).ready(function() {

     $('#mainbox').mouseenter(
         function () {
           $('#infobox').fadeIn();
         }); 
     $('#mainbox').mouseleave(
         function () {
           $('#infobox').fadeOut();
         });

   });

And also blocks:

<div id="mainbox"><div id="infobox" style="display: none;">first block - it works on      this one</div></div>

<div id="mainbox"><div id="infobox" style="display: none;">2nd block - it doesn't work/div></div>

<div id="mainbox"><div id="infobox" style="display: none;">3rd block - it doesn't work</div></div>

Do you guys have any ideas what the problem is?

Upvotes: 1

Views: 155

Answers (2)

Morv
Morv

Reputation: 390

The problem is: That selector targets only the first infobox inside the first mainbox in your document.

In the API you can read:

Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM. This behavior should not be relied on, however; a document with more than one element using the same ID is invalid.

And that, is why your code isn't working.

Hint: Switch ids to classes and bind the mouse events to search inside the div like:

$('.mainbox').mouseenter(
  function () {
    $(this).find('.infobox').fadeIn();
  }); 

$('.mainbox').mouseleave(
  function () {
    $(this).find('.infobox').fadeOut();
});

Upvotes: 2

Gabriel Gartz
Gabriel Gartz

Reputation: 2870

Change id to class:

<div class="mainbox"><div class="infobox" style="display: none;">first block - it works on      this one</div></div>


<div class="mainbox"><div class="infobox" style="display: none;">2nd block - it doesn't work/div></div>

<div class="mainbox"><div class="infobox" style="display: none;">3rd block - it doesn't work</div></div>

Then in JS:

$(document).ready(function() {

 $('.mainbox').mouseenter(
     function () {
       $(this).find('.infobox').fadeIn();
     }); 
 $('.mainbox').mouseleave(
     function () {
       $(this).find('.infobox').fadeOut();
     });
});

Upvotes: 0

Related Questions