views:

70

answers:

4

I'd like to build onmouseover directly into a javascript block. I can do it within a hyperlink but I need to do it in the actual script section for the code im writing. Can I do object.onMouseOver()? Or is there another way to do it? So for example I'd like

<script>
something i can put in here that will make on mouseover work on a specific object
</script>
+2  A: 

Yes. :)

<span onmouseover="alert('Hi there')">Hi there</span>

Do you mean like that?

edited to add:

Ah I see so like this?

<span id="span1">Hi there</span>

<script>
    document.getElementById('span1').onmouseover  = function() {
        alert('Hi there');
    }
</script>   
Joe Simes
+2  A: 

You bind events to HTML elements not javascript blocks. If you are talking about binding events to elements using script, yes you can do it. You can use addEventListener to bind events.

document.getElementById("eleid").addEventListener("mouseOver", myEventMethod, false);
Teja Kantamneni
A: 

You can use addEventListener in Firefox/Chrome/etc. and attachEvent in IE. See this page.

For example,

<div id="cool">Click here!</div>
<script>
    function divClicked()
    {
        // Do some stuff
    }

    var theDiv = document.getElementById("cool");
    if(theDiv.attachEvent)
    {
        // IE
        theDiv.attachEvent('onclick', divClicked);
    }
    else
    {
        // Other browsers
        theDiv.addEventListener('click', divClicked, false);
    }
</script>

If you want to avoid having to write all that code, you can use a JavaScript library (jQuery, Prototype, etc.) to simply your code.

Na7coldwater
+1  A: 

Yes you can so if you have a link somewhere in the page that you want to fire the hover for you can use the following.

http://jsbin.com/asoma4/edit

EDIT: I should add that the attached is just an ugly example to demonstrate that what you want to do can be done. I would look into popular js libraries (jquery, prototype, etc..) to clean this up a lot and make it easier.

spinon