SitePoint Sponsor |
|
User Tag List
Results 1 to 4 of 4
-
Jul 28, 2007, 14:04 #1
- Join Date
- Oct 2005
- Location
- London
- Posts
- 1,678
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
mouseover works in this standards compliant code but onclick doesnt
Hi,
Ive just started re-coding my site and doing all the javascript in a nice standard way....using event listeners etc.
I have a function that set a div to display block when clicked on and display none when clicked on again.........i wrote this code for it and it works when i use mouseover as the function but when i try to use onclick it doesnt work.
Could anyone suggest why?
Heres the code, the line that isnt is the offender is inside the addlisteners function...as i say mouseover works fine...
Code JavaScript:// cross-browser event handling function addEvent(element, evType, fn, useCapture) { if (element.addEventListener) { element.addEventListener(evType, fn, useCapture); return true; } else if (element.attachEvent) { var r = element.attachEvent('on' + evType, fn); return r; } else { element['on' + evType] = fn; } } //add a listener on page load addEvent(window, 'load', addListeners, false); //function to set all the other functions running function addListeners() { var button = document.getElementById('chatButton'); addEvent(button, 'onclick', showChat, false); } //toggle the chat box when a user clicks the show/hide chat button function showChat() { var chat = document.getElementById('chat_box'); if (window.event) { var chatButton = window.event.srcElement; } else { var chatButton = this; } if(chat.style.display == 'none') { chat.style.display = 'block'; chatButton.firstChild.nodeValue = 'Hide Chat'; } else { chat.style.display = 'none'; chatButton.firstChild.nodeValue = 'Show Chat'; } }
any ideas?
-
Jul 28, 2007, 15:05 #2
- Join Date
- Jul 2007
- Posts
- 345
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Should the event in the addEvent function just be 'click' rather than 'onclick'?
-
Jul 29, 2007, 02:10 #3
- Join Date
- Oct 2005
- Location
- London
- Posts
- 1,678
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Yes! Why is that?
Thanks for your reply r51
-
Jul 29, 2007, 02:15 #4
- Join Date
- Jul 2007
- Posts
- 345
- Mentioned
- 0 Post(s)
- Tagged
- 0 Thread(s)
Many modern browsers name events without the 'on' at the beginning. Your script actually adds the 'on' part for those browsers that expect it.
Bookmarks