0

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>
4
  • 3
    Check what is this and you'll get the answer why... Commented Dec 5, 2017 at 10:02
  • provide class or id insteed of 'this', what is this in this code? Commented Dec 5, 2017 at 10:04
  • this is nothing in context you are using it. holding url in id? onclick handlers with functions might cause problems, use event binding instead. Commented Dec 5, 2017 at 10:08
  • pass another parameter as this in function and use it for add/remove class. Commented Dec 5, 2017 at 10:34

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

How would I then pass that through? Like loadIframe(this.data-url, this); ??
I found out myself :D For anyone wondering I did this: this.getAttribute('data-url')
There is a neat way in jquery to do this (imo). I think it is called $.data('url') if your data-attribute is called data-url. Here is a link: api.jquery.com/data.
0

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

check this and this

2 Comments

ouch, 82Tuskers was faster ;)
It would have been better if you could provide the answer directly instead of redirecting them to a different question. This can save a lot of searching for future readers.
0

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');
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.