Leandros López
Leandros López

Reputation: 391

jQuery \ Javascript - if statement does not evaluate correctly

I'm building a webpage with the following codes:

function change () 
{
    if($(this).hasClass("rosaLC"));
    {
        $(this).toggleClass('rosaLCb');
    }
    if ($(this).hasClass('rosaBC'));
    {
        $(this).toggleClass('rosaBCb'); 
    }
}

On the html, the buttons that trigger this function is the follow:

<div class="row">
    <article class="columnLeft">
        <div class=rosa>    
            <button onclick="playVid('crux');change.call(this)" class=rosaLC style="top:28px; left:75px;" ></button>
            <button onclick="playVid('gloria');change.call(this)" class=rosaBC style="top:460px; right:131px;"></button>
        </div>
    </article>
</div>

But, when the function change() is called, the if statement does not evaluate correctly, that is, when the <button> of class rosaLC is clicked, the function change () add to it both classes rosaLCb and rosaBCb, and the original class rosaLC does not come toggled, the button still with the 3 classes: <button onclick="playVid('crux');change.call(this)" class="rosaLC rosaLCb rosaBCb" style="top:20px; left:86px;"></button>

What is wrong?

As a workaround I have split the function in two functions:

function change (thisObj) 
{
    $(thisObj).toggleClass('rosaLC rosaLCb');

}
function change1 (thisObj) 
{
    $(thisObj).toggleClass('rosaBC rosaBCb');
}

And change the html button:

<button onclick="playVid('gloria');change1(this)" class=rosaBC style="top:36px; right:58px;"></button>
<button onclick="playVid('crux');change(this)" class=rosaLC style="top:28px; left:75px;" ></button>

This is the only way that work as I wish, but I still not understanding what is wrong with the original code, mainly concerning the if statement.

Upvotes: 0

Views: 56

Answers (1)

gurvinder372
gurvinder372

Reputation: 68363

You are not defining what to toggle it with

Simply do this

function change () 
{
        $(this).toggleClass('rosaLC rosaLCb');
        $(this).toggleClass('rosaBC rosaBCb'); 
}

Also, pass the element object rather than using this since then it becomes reusable for purpose other than button click (some other event on another element)

function change (thisObj) 
{
        $(thisObj).toggleClass('rosaLC rosaLCb');
        $(thisObj).toggleClass('rosaBC rosaBCb'); 
}

and invoke it as

<button onclick="playVid('crux');change(this)" class=rosaLC style="top:28px; left:75px;" ></button>

Upvotes: 1

Related Questions