Reputation: 23
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
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
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
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:
.addEventListener()
method to the element, with the named function as callbackExample:
const isparta = document.getElementById('isparta');
const activateAlert = () => { alert('ok'); };
isparta.addEventListener('click', activateAlert, false);
Upvotes: 1