Walaupun tutorial sejenis sudah banyak yang membahas, tidak salahnya juga, jika saya membahasnya lagi diblog ini, hitung hitung menambah perbendaharaan pengetahuan tentang javascript.
JavaScript
function toggleClass(selectorID,newClass){
var selector = document.getElementById(selectorID);
//metode classList
if(selector.classList)
selector.classList.toggle(newClass);
else{
//jika tidak support classList
var splitClass = selector.className.split(" "),
i = splitClass.indexOf(newClass);i>=0?splitClass.splice(i,1):splitClass.push(newClass),
selector.className=splitClass.join(" ")
}
}
HTML Example
<button onclick='toggleClass("demo","red");'>Toggle Class</button>
<div class='boxs' id='demo'></div>
Penjelasan :
- Yang bergaris bawah dengan kata
demo
adalah targetID
dari element yang ditargetkan. - Yang bergaris bawah dengan kata
red
adalah nama kelas (className) yang ingin disematkan.
Demo :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Triksonic Demo</title>
<style>
.boxs {
width : 100px;
height : 100px;
border : 1px solid silver;
}
.red {
background : red;
}
</style>
</head>
<body>
<button onclick="toggleClass('demo','red');">
Toogle Class
</button>
<div class="boxs" id="demo"></div>
<script>
function toggleClass(selectorID,newClass){
var selector = document.getElementById(selectorID);
//metode classList
if(selector.classList)
selector.classList.toggle(newClass);
else{
//jika tidak support classList
var splitClass = selector.className.split(" "),
i = splitClass.indexOf(newClass);i>=0?splitClass.splice(i,1):splitClass.push(newClass),
selector.className=splitClass.join(" ")
}
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Triksonic Demo</title> <style> .boxs { width : 100px; height : 100px; border : 1px solid silver; } .red { background : red; } </style> </head> <body> <button onclick="toggleClass('demo','red');"> Toogle Class </button> <div class="boxs" id="demo"></div> <script> function toggleClass(selectorID,newClass){ var selector = document.getElementById(selectorID); //metode classList if(selector.classList) selector.classList.toggle(newClass); else{ //jika tidak support classList var splitClass = selector.className.split(" "), i = splitClass.indexOf(newClass);i>=0?splitClass.splice(i,1):splitClass.push(newClass), selector.className=splitClass.join(" ") } } </script> </body> </html>
Posting Komentar