2

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>

1

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

1

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>

3 Comments

how can i do this with if query make an event if clicked
It's not done like that. You don't need and if to check if the button is clicked or not. The click event is saved in the DOM and it is fired when you click the button. No need for if, the browser does this automatically.
@EyüpFidan please accept the answer if it's what you want.
1

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"); 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.