Hi,

I have pretty just started javascript and I have to say it is the hardest language to learn probably due to the lack of official documentation or something like that. If someone can point me in the right direction for documentation, that'll be great. On the other hand, php is so easy to learn because of the official documentation and tutorial sites.

So, here's the thing. I have a multiple elements that are in the same class. How can I get those elements to respond to an event without actually having to with onmouseover="this.style.background = '#687168';" or something for every single tag. I don't want to put them in with php because it is just messy.

Recommended Answers

All 11 Replies

You could give them all the same name (because sadly there isn't a function to grab class name) grab them all and then attach an event listener via:

var elements = document.getElementsByName("mouseOverName"); /* NOTE Remember the s in getElements */
for(var i = 0; i < elements.length; i++)
{
   elements[i].addEventListener('onmouseover',doSomething,false);

   function doSomething() {
	this.style.backgroundColor = '#cc0000';
   }
}

You will have to do the above after the dom has loaded by putting the above in a function and attaching the function to the documents onload function

<body onload=attachListeners();>

or you can look into jQuery and use

$(document).ready(function(){
   $(".yourClassNameHere").mouseover(function()
    {
         this.style.backgroundColor = '#cc0000';
    });
});

Some links to check out:
http://www.javascript.com/
http://api.jquery.com/mouseover/
http://jquery.com/
http://www.quirksmode.org/js/events_advanced.html

How can I get those elements to respond to an event without actually having to with onmouseover="this.style.background = '#687168';" or something for every single tag.

This

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta name="generator" content=
    "HTML Tidy for Windows (vers 25 March 2009), see www.w3.org">
    <script type="text/javascript">

window.onmouseover = setBack;

function setBack(e) {
    e = e || event;
    var that = e.srcElement || e.target;
    if (that.tagName == 'TD') {
        if (that.getAttribute('class') == 'hot') {
            that.style.backgroundColor = 'red'
        }
    }
}

    </script>
    <title></title>
  </head>
  <body>
    <table>
      <tr>
        <td class='cold' style='background-color:blue'   height="100" width="100"></td>
        <td class='warm' style='background-color:pink'   height="100" width="100"></td>
        <td class='hot'  style='background-color:maroon' height="100" width="100"></td>
      </tr>
    </table>
  </body>
</html>

does what scrappedcola did in a way that you may [or may not :)] find useful.

Thank you very much :)

I'll give those a try. I'll come back with results. :)

Best to use cascading style sheets for this particular feature.

<style type="text/css">
.MyElement {
 background-color: #861786; /*whatever the normal background should be, optional*/
}
.MyElement:hover {
 background-color: #687168; /* background during mouse roll-over*/
}
</style>

// ....
<div id='my_div' class='MyElement'>My Div</div>

The advantage with CSS is that it still works when javascript is turned off.
If you really need to use javascript:

var element=document.getElementById('my_div');
element.addEventListener('mouseover',function () {
	this.style.backgroundColor = '#687168';
},false)

Of course you will also need to set up and event handler for mouse-out events too.

Hi,

I have pretty just started javascript and I have to say it is the hardest language to learn probably due to the lack of official documentation or something like that. If someone can point me in the right direction for documentation, that'll be great. On the other hand, php is so easy to learn because of the official documentation and tutorial sites.

So, here's the thing. I have a multiple elements that are in the same class. How can I get those elements to respond to an event without actually having to with onmouseover="this.style.background = '#687168';" or something for every single tag. I don't want to put them in with php because it is just messy.

Best to use cascading style sheets for this particular feature.

<style type="text/css">
.MyElement {
 background-color: #861786; /*whatever the normal background should be, optional*/
}
.MyElement:hover {
 background-color: #687168; /* background during mouse roll-over*/
}
</style>

// ....
<div id='my_div' class='MyElement'>My Div</div>

The advantage with CSS is that it still works when javascript is turned off.
If you really need to use javascript:

var element=document.getElementById('my_div');
element.addEventListener('mouseover',function () {
	this.style.backgroundColor = '#687168';
},false)

Of course you will also need to set up and event handler for mouse-out events too.

Thanks for the reply. The onmouseover() was actually just an example because I actually wanted to use onchange() . I appreciate the comment though.

This

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <meta name="generator" content=
    "HTML Tidy for Windows (vers 25 March 2009), see www.w3.org">
    <script type="text/javascript">

window.onmouseover = setBack;

function setBack(e) {
    e = e || event;
    var that = e.srcElement || e.target;
    if (that.tagName == 'TD') {
        if (that.getAttribute('class') == 'hot') {
            that.style.backgroundColor = 'red'
        }
    }
}

    </script>
    <title></title>
  </head>
  <body>
    <table>
      <tr>
        <td class='cold' style='background-color:blue'   height="100" width="100"></td>
        <td class='warm' style='background-color:pink'   height="100" width="100"></td>
        <td class='hot'  style='background-color:maroon' height="100" width="100"></td>
      </tr>
    </table>
  </body>
</html>

does what scrappedcola did in a way that you may [or may not :)] find useful.

I've looked at both sets of codes and I think I'll go with scrappedcola's one because your one is a lot more advanced (IMO). :)

Thanks everyone :D

Best to use cascading style sheets for this particular feature.

Caution: will not work in Firefox 'quirks mode'.

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

or equivalent is required.

window.onclick = setBack;

That won't work in IE8. Sloppy of me :D

document.getElementsByTagName('BODY')[0].onclick = setBack;

works in 'all' browsers.

This little toy

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta name="generator" content=
    "HTML Tidy for Windows (vers 25 March 2009), see www.w3.org">
    <style type="text/css">
	.other { background-color: silver; }
	.other:hover { background-color: aqua; }
    </style>
    <title></title>
  </head>
  <body>
    <div class='other'>
      Firefox must not be in 'quirks mode' for this to work as coded.
    </div>
    <table>
      <tr>
        <td class='other' height="100" width="100"></td>
        <td class='cold' style='background-color:blue' height="100" width="100"></td>
        <td class='warm' style='background-color:pink' height="100" width="100"></td>
        <td class='hot' style='background-color:maroon; color:white' height="100" width="100">
          IE must be in 'standards mode' for this to work as coded.
        </td>
      </tr>
    </table>

    <script type="text/javascript">

      document.getElementsByTagName('BODY')[0].onclick = setBack;

      function setBack(e) {
        e = e || event;
        var that = e.srcElement || e.target;
        if (that.tagName == 'TD') {
            if (that.getAttribute('class') == 'hot') {
                that.style.backgroundColor = 'red'
            }
        }
      }

    </script>
  </body>
</html>

combines both approaches.

Where CSS :hover is supported, it is clearly superior to javascript onmouseover= [thank you for the reminder, witerat :)].
In all other cases, javascript is necessary.

That won't work in IE8. Sloppy of me :D

document.getElementsByTagName('BODY')[0].onclick = setBack;

works in 'all' browsers.

This little toy

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
  <head>
    <meta name="generator" content=
    "HTML Tidy for Windows (vers 25 March 2009), see www.w3.org">
    <style type="text/css">
	.other { background-color: silver; }
	.other:hover { background-color: aqua; }
    </style>
    <title></title>
  </head>
  <body>
    <div class='other'>
      Firefox must not be in 'quirks mode' for this to work as coded.
    </div>
    <table>
      <tr>
        <td class='other' height="100" width="100"></td>
        <td class='cold' style='background-color:blue' height="100" width="100"></td>
        <td class='warm' style='background-color:pink' height="100" width="100"></td>
        <td class='hot' style='background-color:maroon; color:white' height="100" width="100">
          IE must be in 'standards mode' for this to work as coded.
        </td>
      </tr>
    </table>

    <script type="text/javascript">

      document.getElementsByTagName('BODY')[0].onclick = setBack;

      function setBack(e) {
        e = e || event;
        var that = e.srcElement || e.target;
        if (that.tagName == 'TD') {
            if (that.getAttribute('class') == 'hot') {
                that.style.backgroundColor = 'red'
            }
        }
      }

    </script>
  </body>
</html>

combines both approaches.

Where CSS :hover is supported, it is clearly superior to javascript onmouseover= [thank you for the reminder, witerat :)].
In all other cases, javascript is necessary.

Looks nice. Could you please explain each part though? Thanks for all you help

please explain

These notes refer to my 'toy', above.

Without lines 1-2 (or an equivalent declaration that invokes 'standards mode') line 9 [from witerat] won't work in Firefox and line 26 won't work in IE.

Line 30 causes all onclick events to be handled by the javascript function named setBack , so it will not be necessary to put an onclick= action on each element.

Lines 32-40 are the function.

Lines 33-34 are for browser independence:
in IE, [window.]event is defined and its .srcElement property points to the originating element; e [the formal parameter] will be 'undefined' at run time
in all others, a reference to the event is passed in as the calling parameter and its .target property points to the originating element; [window.]event will be 'undefined' at run time

Line 35 limits the operation to 'TD' elements [and could be made much more specific if required by the situation]; since all onclick events are going to pass through this function, it is necessary to avoid doing anything on events from "other" elements.

Small note: I chose the variable name 'that' deliberately; its sense is the opposite of 'this' (the keyword that would be used on "the other side" [in an on___= action]).

These notes refer to my 'toy', above.

Without lines 1-2 (or an equivalent declaration that invokes 'standards mode') line 9 [from witerat] won't work in Firefox and line 26 won't work in IE.

Line 30 causes all onclick events to be handled by the javascript function named setBack , so it will not be necessary to put an onclick= action on each element.

Lines 32-40 are the function.

Lines 33-34 are for browser independence:
in IE, [window.]event is defined and its .srcElement property points to the originating element; e [the formal parameter] will be 'undefined' at run time
in all others, a reference to the event is passed in as the calling parameter and its .target property points to the originating element; [window.]event will be 'undefined' at run time

Line 35 limits the operation to 'TD' elements [and could be made much more specific if required by the situation]; since all onclick events are going to pass through this function, it is necessary to avoid doing anything on events from "other" elements.

Small note: I chose the variable name 'that' deliberately; its sense is the opposite of 'this' (the keyword that would be used on "the other side" [in an on___= action]).

mhmm thanks for the explanation. I guess this technique is a lot more advance than the earlier one but I think I'll keep this example in mind for when I need it again.

Thanks again :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.