Question

I am using this code to load some content of a div as well as change the color of the tab the user clicked on. I'm having trouble figuring out how to make the background color change back once the user clicks on something else. How would I do that?

$(function() {
        $('#tab-1').click(function() {
            var tabcontent = "<?php echo preg_replace("/\r?\n/", "\\n", addslashes($tabcontent[0]));?>";
            document.getElementById('top-tabs-content').innerHTML = tabcontent;
            $(this).css("background-color","#F7C703");
        });
    });
Was it helpful?

Solution

$(function() {
    $('#tab-1').click(function() {
        var tabcontent = "<?php echo preg_replace("/\r?\n/", "\\n", addslashes($tabcontent[0]));?>";
        document.getElementById('top-tabs-content').innerHTML = tabcontent;
        $('.tabclass').css("background-color","#defaultcolour");
        $(this).css("background-color","#F7C703");
    });
});

Add a class to the elements, then before applying the colour to clicked element, reset all the elements with the default colour.

OTHER TIPS

You can bind a click handler to the document object and use the .closest() method:

$(document).on('click', function(e) {
    if ( !$(e.target).closest('#tab-1').length ) {
       $('#tab-1').css("background-color", '');
    }
});

http://jsfiddle.net/6g8g7/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top