Sora Keyheart Sora Keyheart - 4 years ago 61
jQuery Question

Better ways to write this JQuery code

When the page load/reload I want to keep the first button with a background-color, and when another button is clicked, that first button color disappear.

I have made this code for it:



$(document).ready(function(){
$(".target1").css("background-color", "red");
$(".target1").css("color", "white");
$(".target2").click(function(){
$(".target1").css("background-color", "transparent");
$(".target1").css("color", "black");
$(".target2").css("background-color","red");
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="collapse3">
<ol>
<button class="target1" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/1.html')">F01-Fabrication-1</button><br>

<button class="target2" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/2.html')">F01-Fabrication-2</button><br>

<button class="target3" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/3.html')">F01-Fabrication-3</button><br>

<a class="target4" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/4.html')">F01-Fbuttonbrication-4</button><br>

<button class="target5" type="button" onclick="setURL('imgs/projects/FAB/F01-Fabrication/5.html')">F01-Fabrication-5</button><br>
</ol>
</div>





I have lots of other buttons, so doing this kind of code in Jquery I think it isn't the best practice...I need help to explain to me a better way to do this? I will appreciate your teachings!

Thanks

Answer Source

You want the this function:

$(document).ready(function() {
  $(".target").css("color", "black").css("background-color", "white");
  $(".target1").css("background-color", "red");
  $(".target1").css("color", "white");
  $(".target").click(function() {
    $(".target1").css("background-color", "none");
    $(".target").css("color", "black").css("background-color", "white");
    $(this).css("background-color", "red");
  });
});
<button class="target target1" type="button">
  Button 1
</button>
<button class="target target2" type="button">
  Button 2
</button>
<button class="target target3" type="button">
  Button 3
</button>
<button class="target target4" type="button">
  Button 4
</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

JSFiddle Example

Hope this helps!

EDIT: Moved to code snippet

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download