Here I will show how to change classes in jQuery and to use classes and ids. The idea of the sample is really simple – we have two divs – one clickable and the other one not. Once we click the clickable div, the other one changes its color.
How it is done? Simply with one click function and one if-else in jQuery. Initially we assign to the second div the class “show_div_red” and once we click on the first div, we change the class to a “show_div_green|, which has a green background. And it somehow works 🙂
Pretty much that is the whole story. The code comes here:
HTML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>RegEx Tool</title> <link rel="stylesheet" type="text/css" href="my_style.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="my_js.js"></script> </head> <body> <div id="header">Click</div> <div id="main" class="show_div_red"> Check this out! :) </div> </body> </html> |
CSS:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#main,#header { margin: 25px; border-radius: 25px; border: 2px solid #73AD21; padding: 20px; } div.show_div_red{ background: coral; } div.show_div_green{ background: greenyellow; } |
JS:
1 2 3 4 5 6 7 8 9 10 |
$(document).ready(function () { $("#header").click(function() { console.log($("#main").attr("class")); if ($("#main").attr("class") == "show_div_red") { $("#main").attr("class","show_div_green"); } else { $("#main").attr("class","show_div_red"); } }); }); |
If for any reason you would like to see it in GitHub, you may see it here!
Enjoy it 🙂