How to make specific button to stay active ? CSS, Javascript - Stack Overflow

admin2025-04-18  1

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>

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>
Share Improve this question edited Dec 7, 2015 at 1:50 Josh Crozier 242k56 gold badges400 silver badges313 bronze badges asked Jan 29, 2013 at 15:13 Edgars PavlovicsEdgars Pavlovics 111 gold badge1 silver badge4 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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 pletely right, but his jQuery code does horrible things on the background, see the ments:

$(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 mand
    // 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 pletely by not supporting it.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744954712a276538.html

最新回复(0)