Anraiki
Anraiki

Reputation: 796

Function not being initialized

I am facing a very odd problem. Everything should work correctly, however, the function refuses to run.

I have similar functions that run just fine but this will not initialize unless I run it through the console.

This is the code:

$(".like").click(function() {
    number = parseInt($(this).text());
    $(this).text(number+1).addClass("iLike").removeClass("like");
    delete number;
});

$(".iLike").click(function() {
    number = parseInt($(this).text());
    $(this).text(number-1).addClass("like").removeClass("iLike");
    delete number;
});

The site I am trying to run it @ is: ~~~~

It is in the scripts but, it's not running. I don't know why.

HTML:

<button id="like-85" class="like " type="button">3</button>

Problem: Injecting HTML into the DOM would not alter the source and would not attached certain functions to the injection.

Solution: Insert within the tag, which is , an event such as onclick:

Upvotes: 1

Views: 141

Answers (2)

rgin
rgin

Reputation: 2311

I checked the source. You don't have any elements on that page with a class like or iLike. So basically, you're binding the click() to nothing.

Update: It seems that you're adding the button element to the apge via js? If so, change click( function() .. to .on('click',function() ..

i.e.

$(".like").on('click', function() {
    number = parseInt($(this).text());
    $(this).text(number+1).addClass("iLike").removeClass("like");
    delete number;
});

$(".iLike").on('click', function() {
    number = parseInt($(this).text());
    $(this).text(number-1).addClass("like").removeClass("iLike");
    delete number;
});

Documentation: http://api.jquery.com/on/

Upvotes: 1

Andrew Ngo
Andrew Ngo

Reputation: 762

It has to be inside the $(document).ready()

Upvotes: 1

Related Questions