user1989
user1989

Reputation: 31

passing arguments to a javascript function

This is a javascript function

<script>
function func1(var g){
alert(document.getElementsByTagName('p')[0].innerHTML);
}
</script>

how to pass value 0 from function call to function definition above.

<p onmouseover="func1(0)";>First para</p>

Upvotes: 0

Views: 58

Answers (2)

Andy
Andy

Reputation: 63514

Since you're using [0] to target the first paragraph when you mouseover it your function should be;

function func1(g){
  alert(document.getElementsByTagName('p')[g].innerHTML);
}

A more canonical JS approach is to attach an event listener to your elements with JavaScript instead of inlining the code:

var paras = document.getElementsByTagName('p');

[].slice.call(paras).forEach(function (el, i) {
  el.addEventListener('mouseover', func1.bind(func1, i), false);
});

function func1(g){
  console.log(paras[g].innerHTML);
}

DEMO

But perhaps the best way is to use event delegation so that you're not adding listeners to all the elements. Add an event listener to a parent element and catch the events from the paras as they bubble up the DOM:

var div = document.getElementById('paras');

div.addEventListener('mouseover', func1, false);

function func1(e) {
  var el = e.target;
  if (el.nodeType === 1 && el.nodeName === 'P') {
    console.log(el.innerHTML);
  }
}

DEMO

Upvotes: 1

Jagdish Idhate
Jagdish Idhate

Reputation: 7742

Change it to

<script>
function func1(g){
  alert(document.getElementsByTagName('p')[0].innerHTML);
}
</script>

You need to see console log for relevant errors that pop up.

In this case you are declaring variable in function arguments which is not allowed, you can find out more about function here.

Upvotes: 2

Related Questions