Skip to content Skip to sidebar Skip to footer

Change Div Style Onclick

I have 2 tabs at the top of a page. When one tab is clicked, I would like that tab to have an 'active' class and the other tab to have an 'inactive' class so that the user can see

Solution 1:

another non-jQuery solution could be the following that works with more than two div:

functionchangeClass(elClass) {
  var divsLenght = document.getElementsByTagName("div").length;
  for (var i = 0; i < divsLenght; i++) { 
    document.getElementsByTagName("div")[i].className = "tabInactive"; 
  } 
  elClass.className = "tabActive";   
}

Demo:http://jsbin.com/opetec/2

Solution 2:

<divclass="tabInactive"onclick="this.classname='tabActive'"></div>

if using jquery:

$("div.tabInactive").click(function() {
    $("div.tabInactive").removeClass("tabActive");
    $(this).addClass("tabActive");
});

Solution 3:

here's a solution that doesn't use any jQuery! it does assume there is only 2 tabs thought.

http://jsfiddle.net/nYpV3/

<div id="tab1" onclick="setToActive(this, 'tab2');">
Option 1
</div>

<div id="tab2" onclick="setToActive(this, 'tab1');">
Option 2
</div>

function setToActive(me, otherId){

    me.className='active';
    document.getElementById(otherId).className='inactive';
}

Solution 4:

Give your tabs a class of "tab"... HTML:

<divclass="tab">
...
</div><divclass="tab">
...
</div>

JS:

functiongetByClass(_class, elem) {
    var i, result = [], elems = document.getElementsByTagName("div"); //get the elementsfor (i = 0; i < elems.length; i++) {
        if (elems[i].className.indexOf(_class) !== -1) { //if the elements have the class passed in, add it to the result array
            result.push(elems[i]);
        }
    }
    return result;
}
var i, tabs = getByClass("tab", "div"); //get all divs with class tabfor (i = 0; i < tabs.length; i++) { //for each tab...
    tabs[i].onclick = function() { //wire up it's click event...//to clear the other tabs...var j;
        for(j=0; j < tabs.length; j++) {
           tabs[j].className = tabs[j].className.replace(" active", "");
        }
       this.className += " active"; //where active is a class predefined in the CSS 
    };
}

http://jsfiddle.net/thomas4g/pqMq2/12/

Solution 5:

Try this using jQuery

<divclass="tab active">
Option 1
</div><divclass="tab">
Option 2
</div><script>
$(function(){
    $(".tab").live("click", function(){
        $(".tab").removeClass("active");
        $(this).addClass("active");
    });
});
</script>

Post a Comment for "Change Div Style Onclick"