2

I am having an issue with a single line of javascript/jquery. I am attempting to select all objects with a given class and then create a trigger on another object using the id stored in the first objects class.

The JS/JQ:
$('.navs').click(function(){$("#"+$(this).attr('tab')+"").trigger('click');})

The HTML:
<img alt="" class="thumbnail" src="gamedev_thumb.png" class="navs" tab="gamedev"/>

I am not sure if this matters, but this code is in a page fragment that is loaded into a div on the main page. I have tabs at the top to control navigation, and for simplicity I would like the image to trigger a click on the appropriate tab on top.

1 Answer 1

5

You have two times a class attribute. You can definitely put several class names within the same class attribute:

<img alt="" class="thumbnail navs" src="gamedev_thumb.png" tab="gamedev"/>

If the fragment is loaded with ajax after the page has loaded, unfortunately, your selector $('.navs') has already run and your image will not be part of it, you have to execute your piece of javascript after the fragment has loaded and been appended to the document.

I don't know how you load the fragment but one way is to use the callback of the .load() method if you used it:

$('#mydiv').load(url, function() {
    $('.navs').click(function(){
        $("#"+ $(this).attr('tab') + "").trigger('click');
    })
});

Note that if you load a fragment with the load method (for instance "mypage.html #mydiv"), all javascript blocks will be removed.

jQuery .load()

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

4 Comments

I put the JS in the page fragment so it runs when the page is loaded. Correcting the class tag fixed it. Thanks so much!
If the answer he gave you fixed your problem, you should mark it as such.
I had to wait for it to let me :) I just now came back to do so.
Glad it helped you ! Anytime :-)

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.