Eyüp Fidan
Eyüp Fidan

Reputation: 23

Pure Javascript Div Click Check

I have div containing svg like this i want to do something when this dive click event how can i do

Code

if (document.getElementById("isparta").onclick) {
  alert('ok')
};
<g id="isparta" data-plakakodu="32" data-alankodu="246" data-iladi="Isparta">
  test click
</g>

Upvotes: 2

Views: 541

Answers (3)

Bikram Kumar
Bikram Kumar

Reputation: 443

You can also define the onclick function in HTML.

<g id="isparta" data-plakakodu="32" data-alankodu="246" data-iladi="Isparta" onclick="alert('hello')">
  test click
</g>

OR if you want more lines of code just give the name of the function, in html and define the function in JavaScript:

<g id="isparta" data-plakakodu="32" data-alankodu="246" data-iladi="Isparta" onclick="myFunction()">
  test click
</g>

function myFunction() {
  alert("hello"); 
}

Upvotes: 1

Hassen Ch.
Hassen Ch.

Reputation: 1751

There you go. It's just a syntax mistake. onclick should receive a function like following:

document.getElementById("isparta").onclick = function() {
  alert("hello");
}
<g id="isparta" data-plakakodu="32" data-alankodu="246" data-iladi="Isparta">
  test click
</g>

Upvotes: 1

Rounin
Rounin

Reputation: 29453

You are on the right lines.

There are several ways to attach an Event Listener like onclick but a standard unobtrusive approach in modern Javascript would be to:

  • grab the DOM element
  • declare a named function
  • apply the .addEventListener() method to the element, with the named function as callback

Example:

const isparta = document.getElementById('isparta');

const activateAlert = () => { alert('ok'); };

isparta.addEventListener('click', activateAlert, false);

Upvotes: 1

Related Questions