简体   繁体   中英

How to make specific button to stay active ? CSS, Javascript

having a problem, I have a javascript content switcher on a page, but I can't seem to get one thing working - how to make a clicked button stay active after it's clicked?

Here's a code: JS

<script type="text/javascript">
function switch1(div) {
var option=['one','two','three'];
for(var i=0; i<option.length; i++) {
if (document.getElementById(option[i])) {
obj=document.getElementById(option[i]);
obj.style.display=(option[i]==div)? "block" : "none";
}
}
}

window.onload=function () {switch1('one');}
</script>

CSS

#switchables li a {
    color: #262626;
    text-decoration: none;
    display: inline-block;
    padding-top: 14px;
    padding-right: 34px;
    padding-bottom: 10px;
    padding-left: 33px;
    background-image: url(img/catButBcgr.jpg);
    border-right-width: 1px;
    border-left-width: 1px;
    border-right-style: solid;
    border-left-style: none;
    border-right-color: #E1E1E1;
    border-left-color: #FFF;
}
#switchables li a:hover {
    background-image: url(img/catButBcgrH.jpg);
}
#switchables li a:active {
    background-image: url(img/catButBcgrA.jpg);
}

HTML

 <ul id="switchables">
   <li><a class="active" href="javascript:void[0];" onclick="switch1('one');">OVERVIEW</a></li>
   <li><a class="active" href="javascript:void[0];" onclick="switch1('two');">CATEGORY</a></li>
   <li><a class="active" href="javascript:void[0];" onclick="switch1('three');">CATEGORY</a></li>
</ul>

You need to make an "Active" class and add it to the button when clicked.

#switchables a:active, #switchables a.active {
    background-image: url(img/catButBcgrA.jpg);
}

It's easy using jQuery:

$(document).ready(function() {
    myInit()
})

function myInit() {
    $('#switchables a').click(function() {
        $('#switchables a').removeClass('active')
        $(this).addClass('active')
    })
}

This is a nice opportunity to learn. Diodeus' answer is completely right, but his jQuery code does horrible things on the background, see the comments:

$(document).ready(function() {
    myInit()
})

function myInit() {
  // on the following line, jQuery creates an array of objects (a tags)
  // (costly operation!) and adds click listener to each of them
  $('#switchables a').click(function() {
    // on the following line, jQuery creates the crazy God object again
    // and throws it off after this command
    // for each a tag and tries to remove class active from it
    // in only one case it actually does something - mere class removal
    // btw removeClass is ridiculous function if you dig into jQuery 1.10 source  
    $('#switchables a').removeClass('active')
    // this = the source of click event, not jQuery object
    $(this).addClass('active')
  })
}

This is just a very short code, now imagine you write whole web this style. It will be observably slower, consuming much more resources.

If you insist on jQuery, try to write reusable code a little:

function myInit() {
  // jQuery object is created only once
  var $anchors = $('#switchables a');
  $anchors.click(function() {
    // ...and reused here
    $anchors.removeClass('active')
    $(this).addClass('active')
  });
}

But you'd do much better job using native javascript

var items = document.querySelectorAll("#switchables a");
var prev = items[0];
[].forEach.call(items,function(item) {
  item.addEventListener("click",function() {
    // no need to loop every a tag here
    prev.classList.remove("active");
    item.classList.add("active");
    // remember previous active a tag
    prev = item;
  });
});

document.querySelectorAll is a live collection which is something that can't be achieved by any javascript library, it is implemented in underlying and more effective code of the browser.

Advice Don't use jQuery until you know Javascript well. Without that knowledge, you will be able to implement just basic animations, copy&paste some plugins and nothing more. And when you know Javascript on some level, you will probably see very little reason to use jQuery anymore.

In the code above, jQuery can be easily removed:

1: $(document).ready(handler) -> document.addEventListener("readystatechange",handler);

2: $('#switchables a') -> document.querySelectorAll("#switchables a");

3: $(nodeList).click(handler) ->

[].forEach.call(nodeList,function(node) {
  // you can reuse node here, unlike the jQuery
  node.addEventListener("click",handler);
});

4: $(node).removeClass(className) -> node.classList.remove(className)

5: $(node).addClass(className) -> node.classList.add(className)

It is a few chars longer. But it is more reusable, readable, effective and it is not God object or Cargo cult programming.

The native codes above are javascript standards and are supported in any decent browser. Three years ago, when Diodeus provided his answer, IE8 was an issue here. But it is dead now (under 2% worldwide according to gs.statcounter). Help it die completely by not supporting it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM