jerneva jerneva - 7 months ago 9
Javascript Question

How to make a colour change on click, to load with one button selected

I have a colour change on click, that changes colour when another button is pressed, then goes back to normal. but i was wondering how i would have one button that is highlighted on load of page, then become un-highlighted when another button is pressed, and goes back to the normal settings.

My scripting works but just doesn't highlight one of my toggles on page load. i wanted my account button to be highlighted on page load. i have tried but have been unlucky. Please help!



<script>
$(document).ready(function() {
$('.sidebar h3').on('click', function() {
$('.sidebar h3').css('color', 'black');
$(this).css('color', 'red');
$('h3#order').trigger('click');

});
});
</script>

<div class="sidebar">
<a id="order" class="header" href="#" onclick="toggleVisibility('Order');"><h3 id="orderr">Orders</h3></a>
<div id="Order" style="display: none;"></div>

<a id="restt" class ="header"href="#" onclick="toggleVisibility('Rest');"><h3>Your Restaurants</h3></a>
<div id="Rest" style="display: none;"><div>
<!-- account -->
<a id="francc" name="account" class ="header" href="#" onclick="toggleVisibility('Franc');"><h3 id="open">Your Account</h3></a>
<div id="Franc" style="display: none;"></div>




Answer

First take your $('h3#order').trigger('click') trigger out of your click handler. You want this to trigger on page load not on the click of another h3. Keeping it in the document ready function will cause it to trigger on page load. Also your selector is wrong. the H3 has an ID of 'orderr'. You really shouldn't give everything such similar ID's and there is no need for everything to have an ID.

<script>
        $(document).ready(function() { 
            $('.sidebar h3').on('click', function() {
                $('.sidebar h3').css('color', 'black');
                $(this).css('color', 'red');
            });

            $('h3#orderr').trigger('click');
        });
    </script>