I’m trying to have a button on my website that when is active(on click once) adds target _blank to a href links that has a certain class so they open in a new tab.
This is the code for the button
<li id="toolbar-display">
<dl>
<dt>Display</dt>
<dd id="toolbar-display-newtab" class="first last"><span>New Tab</span></dd>
</dl>
</li>
Then this is a href link class that I would like to add _blank to.
<a class="item-link" href="url">
So for this, I use the following javascript which I modified from http://jsfiddle.net/UJMgQ/2/
<script type="text/javascript">
$(function () {
$('#toolbar-display-newtab').click(function () {
if ($(this).toggleClass('active')) {
$('.item-link').attr('target', '_blank');
} else {
$('.item-link').removeAttr('target');
}
});
});
</script>
The code looks like it’s correct, but unfortunately it doesn’t work and I’m unclear at this point whether it’s not detecting the button’s active state or its not able to add _blank. Any help would be appreciated =)
I’m not exactly sure of what the toggleClass() returns but based on my test, it does not give you a boolean value that you can use for an if else condition..
Why not try hasClass() to detect if the class active is already set then use toggleClass after detecting it.
I tried recoding your post though I’m not sure if I got your logic right.