2

I have button which is "Click me", and mouseover() works for only this button the problem is about new buttons. I cant add css with addClass.

$("button#Clickme").on({

    click:function(){
      $("div.Div").append('<button class="Clicker" >New Button</button>');
    }

});

$("button.Clicker").mouseover(function(){
  $(this).addClass("button");
});
$("button.Clicker").mouseout(function () {
 $(this).removeClass("button");
});
Viral Shah
  • 2,263
  • 5
  • 21
  • 36

4 Answers4

1

Here you are, because you create button dynamically:

      $("button#Clickme").on({

        click: function() {
          $("div.Div").append('<button class="Clicker" >New Button</button>');
        }

      });

      $(document).on('mouseover', 'button.Clicker', function() {
        $(this).addClass("button");
        alert('hhh');
      });

      $(document).on('mouseout', 'button.Clicker', function() {
        $(this).addClass("button");
        alert('hhh');
      });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="Clickme">ClickMe</button>
<div class="Div"></div>

Hope this help.

hungndv
  • 2,121
  • 2
  • 19
  • 20
1

Use a parent, to catch the event, because the buttons don't exist when selecting

$("button.Clicker")

then You should use:

var $parent = $('body');
$parent.on('mouseover','button.Clicker').function(){
  $(this).addClass("button");
});
MoLow
  • 3,056
  • 2
  • 21
  • 41
1

may be the problem is with that you working with on click i think you need to bind .click() event

and i just change the the working with event with my style try may b it will work

    $("button#Clickme").on('click',function(){
          $("div.Div").append('<button class="Clicker" >New Button</button>');      
    });

   $("button.Clicker").mouseover(function(){
      $(this).addClass("button");
   });
   $("button.Clicker").mouseout(function () {
     $(this).removeClass("button");
   });

that might work for you

Himesh Aadeshara
  • 2,114
  • 16
  • 26
1

I think you should use .on() for element that is being added dynamically by script as shown below.

  $(document).on('mouseover', 'button.Clicker', function() {
    $(this).addClass("button");
  });

  $(document).on('mouseout', 'button.Clicker', function() {
    $(this).addClass("button");
  });

Your direct connection to .mouseover() event will work only with the elements that are readily available.

But for dynamically created elements, you should use .on()

Hemal
  • 3,682
  • 1
  • 23
  • 54