TonalDev
TonalDev

Reputation: 583

Button element click event to toggleClass doesn't work

I have a on/off button that is featured here

I have all the elements in place and im expecting the button class .on to initiate when pressed.

Only it wont work no matter what i try.

i added the exact code in jsFiddle, it works there, but not on my page.

I'm adding the HTML inside jquery:

'<section>'+
        '<button id="button" href="#">&#xF011;</button>'+
    '<span>'+
    '</span>'+
'</section>'+

I'm guessing its a conflict between CSS elements but i cant pinpoint the problem.

Any thoughts?

Upvotes: 0

Views: 1785

Answers (4)

koninos
koninos

Reputation: 5337

Try this

 $(document).ready(function(){
      $('#button').click(function(){
         $(this).toggleClass('on');
      });
    });

Upvotes: 2

hohner
hohner

Reputation: 11588

I can see this in your page's HTML:

<script>
   $(function(){
      $('#player').metroPlayer();
   });
</script>
<script type="text/javascript">
   $('#button').on('click', function(){
      $(this).toggleClass('on');
   });
</script>

You need to place your on() function inside the $(function() { ... });

Upvotes: 2

Boaz
Boaz

Reputation: 20220

In jsFiddle you are correctly binding the event within $(document).ready(), while in your own page you are not. So in jsFiddle, the event is correctly bound to the button element only after the DOM is ready, while in your own page the event fails to bind since the element does not exist yet at that stage.

Upvotes: 3

Idrizi.A
Idrizi.A

Reputation: 12010

Try this

<script type="text/javascript">
    $(document).ready(function(){
        $('#button').on('click', function(){
            $(this).toggleClass('on');
        });
    })
</script>

Upvotes: 6

Related Questions