NiceDevelopmentq
NiceDevelopmentq

Reputation: 525

JQuery not adding class on click

I'm struggeling with some code, I have code to when I click a <p> element it changes the iframe src and removes the class 'active' of all the elements in the .html file and then add the class 'active' to the clicked element.

But the class 'active' never gets added to the clicked element.

JAVASCRIPT

function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(this).addClass('active');
};

HTML

<li class="w-100" id="http://whatever.com/" onclick="return loadIframe(this.id);">
    <p>

        <i class="fa fa-id-badge" aria-hidden="true"></i>
        <span class="nav-label">Intranet</span>

    </p>
</li>

Upvotes: 0

Views: 68

Answers (3)

vinod gami
vinod gami

Reputation: 67

You need to correct your code add identifier in correct way.

function loadIframe(url){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $("#"+url).addClass('active');
};

Upvotes: 0

Piotr Płaczek
Piotr Płaczek

Reputation: 610

you can not use $(this).addClass();

check this and this

Upvotes: 0

trk
trk

Reputation: 2228

you could pass the context (element) to the handler. I expect this to work:

loadIframe(this.id, this)

And,

function loadIframe(url, element){
    $('.iframe_settings').attr('src', url);
    $('.nav li').removeClass('active');
    $(element).addClass('active');
};

Let me know if that works for you.

Stray comment: I am not sure if it is a good practice to call url an id. You might find data-attributes useful. Attributes like data-id = "". In fact I would call it data-url.

Upvotes: 2

Related Questions