adding a mouseover to a link through javascript
Asked Answered
C

6

6

Simple quick question....

I have the following link html:

<a href="http://www.site.com/" onmouseover="" />

I have a javascript function which I want to enter some onmouseover information into that link dynamically. So, lets say it then becomes this for example if this javascript function is called:

<a href="http://www.site.com/" onmouseover="alert('howdy')" />

any ideas how to do this?

Coaler answered 2/2, 2011 at 10:58 Comment(1)
what do you mean? Do you want to start an action when the user has the mouse over your link and be able to change this action ?Elevation
C
2

Answer was, using setAttribute() javascript.

Coaler answered 11/2, 2011 at 10:36 Comment(0)
H
7

Add name attribute to and assign onmouseover

<a href="http://www.site.com/" onmouseover="" name="xxx"/> 
document.getelementsbyname('xxx').onmouseover = function() { alert('howdy') } 
Hols answered 2/2, 2011 at 11:8 Comment(1)
The tag name here is "a" not "xxx". You would need to use getElementById and an id attributeZackzackariah
C
2

Answer was, using setAttribute() javascript.

Coaler answered 11/2, 2011 at 10:36 Comment(0)
D
0

I think you want to say: dynamically change your href attribute information then you can do it by jquery

//Write code for prompt box and get value (when mouse-over)
$("a[href='http://www.google.com/']").attr('href', 'YOUR_GET_VALUE')
Deliver answered 2/2, 2011 at 11:8 Comment(0)
P
0

If you can use jquery, see: http://api.jquery.com/hover/

This is better than changing the attribute directly. Your javascript function can dynamically bind/unbind the mouse hover event and execute your alert call.

Otherwise your javascript function will need to dynamically change the attribute but you'll need to work around browser differences to locate the correct element then locate and modify the onmouseover attribute.

Phosgenite answered 2/2, 2011 at 11:11 Comment(0)
S
0

two options:

if it's something small:

<a href="http://www.site.com/" onmouseover="this.href = 'http://stackoverflow.com'" />

if you have something more to do:

<script type="text/javascript">
    function doSomething(elem) {
        elem.href = 'http://stackoverflow.com';
    }
</script>
<a href="http://www.site.com/" onmouseover="doSomething(this)">test</a>

Or as stated before: use jQuery or any other framework to make your life a lot easier

Symptomatology answered 2/2, 2011 at 11:19 Comment(0)
W
0

The following works for jQuery every time

first the javascript:

  $(document).on('mouseenter','.hovLink', function (e) {
       e.preventDefault();
       e.stopPropagation();
       alert('entering ' + e.target.id);
  }).on('mouseleave','.hovLink', function (e) {
       alert('exiting ' + e.target.id);
  });

and here is the HTML

<a href="/link" class="hovLink" id="link1">Link</a>
Worker answered 17/1, 2020 at 15:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.