How do you make this code shorter, i’m very new to jquery but i managed to build what i wanted, but is there another way to do this e.g more nicely.
Thanks!
<script type="text/javascript">
$(document).ready(function () {
$(".genre").click(function () {
$(".sobox").hide();
$(".fobox").fadeIn()
$("#notcurrent").css({"background":"#9aa0ae", "color":"#fefefe"});
$("#current").css({"background":"#2568be", "color":"#fff"});
});
$(".other").click(function () {
$(".fobox").hide();
$(".sobox").fadeIn();
$("#current").css({"background":"#9aa0ae", "color":"#fefefe"});
$("#notcurrent").css({"background":"#2568be", "color":"#fff"});
});
});
</script>
I don’t see any serious issues with your existing code, but you could store the CSS style objects in variables rather than repeating them.
Additionally, so long as all the elements exist in the DOM at the time your click event handlers are defined, you could use cached jQuery selectors for a small performance gain.
i.e. assuming in your first event handler you meant to change the style of the
#notcurrentelement and not a different one#ncurrent, and that thefobox/sobox/current/notcurrentelements exist when the DOM is initially loaded:Long story short, I don’t see a clear way to significantly reduce the size of the code, but there are some ways you could make it a little more efficient while maintaining readability. Other answers show how you could define a single callback function that may result in less code.