luke
luke

Reputation: 245

Call function on div click

I am doing this: <div onclick='alert("xxx")'>Click me!</div> and I see that alert but I want to call on function inside that onclick. I'm trying this but it doesn't work.

  function GetContent(prm){
    alert(prm);
  }

  <div onclick='GetContent("xxx")'>Click me!</div>

I need to call that function inline not assign an id or class to that div and use jQuery. What is the solution?

Upvotes: 6

Views: 95307

Answers (2)

Sarfraz
Sarfraz

Reputation: 382909

Using code inline is bad practice, you need to assign an ID or Class to the div and call function against it eg:

<div class="test">Click me!</div>

$('div.test').click(function(){
    GetContent("xxx");
});

.

I need to call that function inline not assign an id or class to that div and use jquery.

I think you are already doing that with this code:

<div onclick='GetContent("xxx")'>Click me!</div>

Calling function inline without assigning id or class. But as said before, it is not good practice to use inline code.

Upvotes: 17

rahul
rahul

Reputation: 187110

You can give that div a class and then do something like this

$("div.myclass").click(function(){
    GetContent("xxx");
});

<div class="myclass"></div>

This will fire click event to all div elements with class 'myclass'.

But I am not sure why you don't want to give an id to the div element.

Upvotes: 5

Related Questions