user475685
user475685

Reputation: 8329

problem with the div tags

I have the following code

<HTML>
<HEAD>
<style type="text/css">
.setbgcolor{
background-color:blue;

}

</style>
<script type="text/javascript">
function setbg(id){
document.getElementById(id).className = "setbgcolor";

}
</script>
</HEAD>
<BODY>
<div onclick="setbg(this.id)" id="bgcolor">Label1</div>
<div>Label2</div>
</BODY>
</HTML>

Now, the problem is that- when i click on Label2, background color should be removed from the first div and should get applied to the second div. Can someone help me out?

Upvotes: 0

Views: 103

Answers (3)

David Thomas
David Thomas

Reputation: 253496

There is no such event as, perhaps, onunclick in JavaScript; there's blur/onblur, but that requires the element to have had focus before it can be triggered.

That said, working on the assumption that you want only one div to be highlighted at any one time, the following works, albeit you'll have to tailor it to your specific needs:

var buttons = document.getElementsByClassName('button'), curHighlights;

for (i=0; i<buttons.length; i++){
    buttons[i].onclick = function(){
        curHighlights = document.getElementsByClassName('bgcolor');
        if (curHighlights.length) {
            for (h=0; h<curHighlights.length; h++){
                // warning: the following removes _all_ class-names
                curHighlights[h].removeAttribute('class');
            }
        }
            this.className = 'bgcolor';
            this.setAttribute('data-state','1');

    };
}

JS Fiddle demo.

I've removed the onclick event handlers from the in-line html, which makes it a little easier to maintain, although it does look quite messy.

For comparison, however, with jQuery the above could be condensed to:

$('.button').click(
    function(){
        $('.bgcolor').removeClass('bgcolor');
        $(this).addClass('bgcolor');
    });

JS Fiddle demo.

Upvotes: 1

Luc125
Luc125

Reputation: 5857

Probably you need something like a variable that stores the previously clicked div.

For example:

var previouslyClickedDiv = null;

function setbg(id){
    if (previouslyClickedDiv) { previouslyClickedDiv.className = ""; }
    var div = document.getElementById(id);
    div.className = "setbgcolor";
    previouslyClickedDiv = div;
}

Of course you can use a shorter variable name!

Upvotes: 0

Bas Slagter
Bas Slagter

Reputation: 9929

Try to take a look at jQuery. It will make your life easier.

Upvotes: 0

Related Questions