Question

I'm using a Wordpress.org website with a JQuery tabs plugin, each page has 10 posts total, each post has it's own JQuery tab set.

So for Post 1 the tabs are labeled #tabs-1-1, #tabs 1-2, etc.

Post 2 the tabs are #tabs-2-1, #tabs-2-2, etc....each tab set has unique id's.

For each post I have a buy now button inside Tab 1 that links to it's Tab 4 to show purchasing options for the product. I'm trying to find out if it's ok to use this code to jump to tab 4:

POST 1:

<a onclick="$('a[href=#tabs-1-4]').click();">BUY NOW</a>

POST 2:

<a onclick="$('a[href=#tabs-2-4]').click();">BUY NOW</a>

POST 3:

<a onclick="$('a[href=#tabs-3-4]').click();">BUY NOW</a>

And so on and so on. The onclick would appear 10 times on each page. I've read that inline javascript is bad which leads me to creating this post as I want to use the best/safest method possible.

I've read the proper way is to put the function in a js file (unobtrusive javaScript) and call it using an id but since each onclick goes to a different tab hash I don't know if that method will work or how to make it work. I have over 400 posts total so would I write 400 different functions in the js file?

Then there's the issue of which link to use if it's ok to use it:

<a onclick="$('a[href=#tabs-1-4]').click();">BUY NOW</a>
<a href="javascript:void(0)" onclick="$('a[href=#tabs-1-4]').click();">BUY NOW</a>
<a href="#" onclick="$('a[href=#tabs-2-4]').click(); return false;">BUY NOW</a>
Was it helpful?

Solution

If you want to be fancy and have html5 support, I would probably make each link similar to this:

<a class="tabLink" data-href="#tabs-1-4">BUY NOW</a>
<a class="tabLink" data-href="#tabs-2-4">BUY NOW</a>

Script (works for all links at once):

var jqTabHost = ".whateverTheNameOfYourTabElementIs";
$('a.tabLink').click(function() {
    //Something like (not sure exactly):
    var href = $(this).data('href');
    //EITHER
    $('a[href=' + href + ']').click();
    //OR (better)
    $(jqTabHost).tabs( "load", href.substring(1) );
    return false;
});

Without custom attribute support you could use href instead of data-href, and munge the href so it's not quite the same.

The idea behind this is keeping the code as short as possible and separating the data (where something links, in HTML) from the behavior (how to make that link work, in script).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top