Prototype - click event on an image - javascript

I am trying to respond to a click event on a image like so. Why isn't this working?
$$('refresh').each(function(element) {
element.observe('click', respond);
})
function respond(event) {
alert("hello");
}
<img src="images/refresh.jpg" id="refresh" />

Updated
See DEMO
Use $('refresh') instead of $$('refresh'), or $$('#refresh'). But second variant returns array anyway. See links: $ and $$. And I don't understand how do you bind event handler.
All code:
<img id="refresh" src="images/refresh.jpg" />
<script>
$$('#refresh').each(function (element) {
Event.observe(element, 'click', respond);
});
function respond (event) {
alert("hello");
}
</script>

Related

I want to call two functions from one onclick [duplicate]

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

How to make onclick function execute only once? [duplicate]

This question already has answers here:
How to pass parameter to function using in addEventListener?
(4 answers)
What is the difference between a function call and function reference?
(6 answers)
Closed 3 months ago.
I have this code for Google analytics on a button. I need it to be executed only once, so that the user can't change statistics by pressing the button many times. I tried solutions from similar topics, but they don't work. Please help. This is my code.
<script>
function klikaj(i) {
gtag('event', 'first-4', {
'event_category' : 'cat-4',
'event_label' : 'site'
});
}
document.body.addEventListener("click", klikaj(i), {once:true})
</script>
<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">My button</div>
Remove onclick attribute on your button and register listener via JavaScript, as you tried to do:
<div id="thumb0" class="thumbs"
style="border: 1px solid; cursor: pointer; float: left">
My button
</div>
<script>
function klikaj(i) {
console.log(i);
}
document.getElementById('thumb0')
.addEventListener("click", function(event) {
klikaj('rad1');
}, {once: true});
</script>
If your browser doesn't support { once: true } option, you can remove event listener manually:
<div id="thumb0" class="thumbs"
style="border: 1px solid;cursor: pointer;float:left">
My button
</div>
<script>
function klikaj(i) {
console.log(i);
}
function onClick(event) {
klikaj('rad1');
document
.getElementById('thumb0')
.removeEventListener("click", onClick);
}
document
.getElementById('thumb0')
.addEventListener("click", onClick);
</script>
you could use removeAttribute() like this: document.getElementById('thumb0').removeAttribute("onclick");
or you could let the function return false like this: document.getElementById('thumb0').onclick = ()=> false
I would recommend setting a variable and checking its value.
<script>
var clicked = false;
function klikaj(i) {
if (clicked === false) {
gtag('event', 'first-4', {
'event_category' : 'cat-4',
'event_label' : 'site'
});
}
clicked = true;
}
...
</script>
Or removing the onclick event as suggested by others,
<script>
function klikaj(i) {
gtag('event', 'first-4', {
'event_category' : 'cat-4',
'event_label' : 'site'
});
document.getElementById('thumb0).onclick = undefined;
}
...
</script>
Note that once: true is unfortunately not supported in IE and Edge. See https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener
Event Handlers & Listeners
There are three ways* to register an event to an element. The following examples show how to register the click event to a link with the class .once** which calls the function test() when triggered.
Event Listener (recommended)
document.querySelector('.once').addEventListener('click', test);`
On-event Attribute (not recommended)
<a href='#/' class='once'onclick='test()'>Click</a>
On-event Property
document.querySelector('.once').onclick = test;`
*See DOM on-event handlers for details
** .once class is not relevant for #2
Issues
The OP (Original Post) has an event listener (see #1 above) registering a click event to the <body> tag and an on-event attribute (see #2 above) registering the click event to a <div>. Each one calls a function (aka callback function) named klikaj() which is redundant. Clicking the body (which is normally everywhere) isn't useful when you intend to have the user click a div. Should the user click anywhere but the div, klikaj() will be called. Should the user click the div, klikaj() will be called twice. I suggest that you remove both event handlers and replace them with this:
A.
document.getElementById('thumb0').addEventListener("click", klikaj);
Note that klikaj has no parenthesis () because the browser interprets () as to run the function now instead of when the user triggers the registered event (see #1 and #3 above). Should an event handler have additional statements and/or callback functions then an anonymous function should be wrapped around it and normal syntax applies:
B.
document.getElementById('thumb0').addEventListener("click", function(event) {
klikaj();
console.log('clicked');
});
A cleaner alternative is to add extra lines in the definition of the callback function instead and registering events like #A.
Solution
Simply add the following statement as the last line of klikaj():
this.style.pointerEvents = "none";
That will render the clicked tag unclickable. Applied to OP code it should be like this:
<div id="thumb0" class="thumbs">Thumb 0</div>
<script>
function klikaj(event) {
gtag('event', 'first-4', {
'event_category' : 'cat-4',
'event_label' : 'site'
});
this.style.pointerEvents = "none";
}
document.getElementById('thumb0').addEventListener("click", klikaj);
</script>
Demo
The following demo has two links:
.default - a normal link registered to the click event which when
triggered calls test()
.once - a link registered to the click event which when triggered
calls test() and renders the link unclickable.
function test() {
console.log('test');
}
document.querySelector('.default').onclick = function(e) {
test();
}
document.querySelector('.once').onclick = function(e) {
test();
this.style.pointerEvents = 'none';
}
<a href='#/' class='default'>Default</a><br>
<a href='#/' class='once'>Once</a>
There is a problem with the way you are trying to attach your handler function.
The function klikaj(i) returns undefined so you are attaching undefined to the button. If you want to execute klikaj(i) when the button is clicked, put it inside a closure like this:
const button = document.querySelector('button')
const i = 10
function klikaj(i) {console.log('clicked once')}
button.addEventListener('click', () => { klikaj(i) }, {once: true})
<button>Hello world</button>
If the browser does not support the {once: true} you can simulate it using:
const button = document.querySelector('button')
const i = 10
function klikaj(i) {console.log("clicked once")}
function clickOnceHandler(event) {
klikaj(i)
event.currentTarget.removeEventListener('click', clickOnceHandler)
}
button.addEventListener('click', clickOnceHandler)
<button>Hello world</button>
Just use a flag variable and set it upon the first execution:
var handlerExecuted = false;
function clickHandler() {
if (!handlerExecuted) {
console.log("call gtag() here");
handlerExecuted = true;
} else {
console.log("not calling gtag() function");
}
}
document
.getElementById("thumb0")
.addEventListener("click", clickHandler);
<div id="thumb0" class="thumbs">My button</div>
An advance variation that uses closures and could be used on multiple buttons:
function clickHandlerFactory() {
var handlerExecuted = false;
return function() {
if (!handlerExecuted) {
console.log("call gtag() here");
handlerExecuted = true;
} else {
console.log("not calling gtag() function");
}
}
}
[...document.querySelectorAll(".thumbs")].forEach(function(el) {
el.addEventListener("click", clickHandlerFactory());
});
<div id="thumb0" class="thumbs">Button 1</div>
<div id="thumb1" class="thumbs">Button 2</div>
If you want the function to be called only when user clicks the button, you will have remove the click event listener from the body.
To fire your gtag function only once you can change the function definition of klikaj inside the function body itself. After the first call gtag will never be called.
The below code works fine.
<script>
function klikaj(i) {
gtag('event', 'first-4', {
'event_category' : 'cat-4',
'event_label' : 'site'
});
klikaj = function() {};
}
</script>
<div id="thumb0" class="thumbs" onclick="klikaj('rad1')">
My button
</div>

button click jquery not working

Should be a really simple answer but I can't figure it out right now. I have this button:
<button id="logout" type="button">Logout</button>
And it's supposed to run this jQuery code within script tags at the bottom of the body:
$("#logout").addEventListener("click", function () {
alert('Button Clicked');
});
However, no alert pops up. I don't get it. Thanks in advance.
addEventListener is a method of DOM element not of jQuery object which is an array-like structure that contains all the selected DOM elements
To attach event using jQuery, use .on => Attach an event handler function for one or more events to the selected elements
Try this:
$("#logout").on("click", function() {
alert('Button Clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="logout" type="button">Logout</button>
Using JS:
document.getElementById("logout").addEventListener("click", function() {
alert('Button Clicked');
});
<button id="logout" type="button">Logout</button>
Edit: You can get first DOM element from array-like object returned by jQuery selector using $(SELECTOR)[0] or $(SELECTOR).get(0)
addEventListener() method registers the specified listener on the EventTarget.
If you really want to use addEventListener then write the following code:
var el = document.getElementById("logout");
el.addEventListener("click", function () {
alert('Button Clicked');
}, false);
Otherwise do it with jquery
$(document).on("click", "#logout", function () {
alert('Button Clicked');
});
OR
$("#logout").on("click", function () {
alert('Button Clicked');
});
Alternate answer is:
$(document).on("click", "#logout", function() {
alert('Button Clicked');
});
This works on dynamically created elements as well.
You should use on method to use the event handlers in jquery. The addEventListener is a core JavaScript event method.
$("#logout").on("click", function() {
alert('Button Clicked');
});
You may still use addEventListner forcing jQuery code to JavaScript:
$("#logout")[0] //Now, this is JavaScript Object
.addEventListener("click", function () {
alert('Button Clicked');
});
You can use jQuery click/on function for getting the button to work.
Example:
$("#logout").on("click", function () { alert('Button Clicked'); });
$("#logout").click(function () { alert('Button Clicked'); });
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function () {
$("#logout").on("click", function () {
alert('Button Clicked');
});
});
</script>
</head>
<body>
<button id="logout" type="button">Logout</button>
</body>
</html>
If you go to your console like in firebug and type $() you will see the jQuery object that shows the methods and properties of the jquery function/object. There is no addEventListener on this object.
addEventlistener is a method for the DOM. If you want to take advantage of jQuery by "writing less and do more" use jQuery methods like on. This will allow you to add an event handler on an element.
$(document).on("click", "#logout", function() {
alert('button clicked');
});
var element = document.getElementById("logout");
element.addEventListener("click", myFunction);
function myFunction() {
// your code logic comes here
}

button action after insert with jquery not working

i have an button "add" i click it then a save button will append to my div. this is working, but i cant trigger the function of the "save" button. if i paste the "save"- button in the code directly it is working. i cant find my error...
<a class="save" href="#"><img src="images/save.png" alt="save_working" /></a>
<a class="add_row" href="#"><img src="images/icon_add_light.png" alt="add" /></a><br>
<div id="hinzu"></div>
$(".save").click(function() {
alert("saveworking");
});
$(".add_row").click(function() {
$("#hinzu").append(' <a class="save" href="#"><img src="images/save.png" alt="savenotworking" /></a>');
});
Here is an fiddle with it: http://jsfiddle.net/MgcDU/321/
Why isnt this working with the js append method?
It's dynamic, so it does not exist when you're binding the event. For that you would need to delegate the event to an element that actually exists at the time of attaching the event handler :
$("#hinzu").on('click', '.save', function() {
alert("saveworking");
});
Use it like:
$("#hinzu").on('click', ".save", function() {
alert("saveworking");
});
this is because when you try to do the $(".save") it does not exist.
You have to use the on() for monitoring if any new .save are in your doom and assign the event handler.
$("#hinzu").on('click', '.save', function()
{
alert("This Does work");
});
It is not working because the $(".save").click() call binds the onclick handler to all elements with class save which already existed at the point of the call.
To bind the event handler also to elements which did not exist at the time of the binding, you must use $(document).on('click', '.save', function() { [...] })
If you want to save you code, use this:
<script type="text/javascript">
$(function() {
$('.save').click(function() {
alert('saveworking');
});
});
$(function() {
$('.add_row').click(function() {
alert('add_row');
});
});
</script>
One more way to do this:
<script type="text/javascript">
$(document).ready(function () {
$('.save').click(function () {
alert('saveworking');
});
$('.add_row').click(function () {
alert('add_row');
});
});
</script>

Can I have two JavaScript onclick events in one element?

Can we put two JavaScript onclick events in one input type button tag? To call two different functions?
This one works:
<input type="button" value="test" onclick="alert('hey'); alert('ho');" />
And this one too:
function Hey()
{
alert('hey');
}
function Ho()
{
alert('ho');
}
.
<input type="button" value="test" onclick="Hey(); Ho();" />
So the answer is - yes you can :)
However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.
The HTML
click
And the javascript
// get a cross-browser function for adding events, place this in [global] or somewhere you can access it
var on = (function(){
if (window.addEventListener) {
return function(target, type, listener){
target.addEventListener(type, listener, false);
};
}
else {
return function(object, sEvent, fpNotify){
object.attachEvent("on" + sEvent, fpNotify);
};
}
}());
// find the element
var el = document.getElementById("btn");
// add the first listener
on(el, "click", function(){
alert("foo");
});
// add the second listener
on(el, "click", function(){
alert("bar");
});
This will alert both 'foo' and 'bar' when clicked.
There is no need to have two functions within one element, you need just one that calls the other two!
HTML
<a href="#" onclick="my_func()" >click</a>
JavaScript
function my_func() {
my_func_1();
my_func_2();
}
You can attach a handler which would call as many others as you like:
<a href="#blah" id="myLink"/>
<script type="text/javascript">
function myOtherFunction() {
//do stuff...
}
document.getElementById( 'myLink' ).onclick = function() {
//do stuff...
myOtherFunction();
};
</script>
You could try something like this as well
<a href="#" onclick="one(); two();" >click</a>
<script type="text/javascript">
function one(){
alert('test');
}
function two(){
alert('test2');
}
</script>

Categories