I have got a button wrapped inside a div.
The problem is that if I click the button, somehow the click function is triggered from the div instead of the button.
Thats the function I have for the click event:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
}
Thats my HTML (after is is created dynamically!!):
<div id="ButtonDiv">
<div class="Line1" id="Line1Software">
<button class="Line1" id="Software">Test</button>
</div>
</div>
So now myVariable from the click function is 'Line1Software' because the event is fired from the div instead of the button.
My click function hast to look like this because I am creating buttons dynamically.
Edit:
This is how I create my buttons and wrapp them inside the div
var c = $("<div class='Line1' id='Line1Software'</div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you are trying to add an event listener to the button you should probably be using $('#Software') instead of $('#ButtonDiv')
The real problem is that neither the div nor the button have an id.
You code with the example html actually fires twice, once for each element since the event will bubble up and match both elements (since they are .Line1)
If you only want it to match the innermost element, then use return false to stop the bubbling.
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
console.log(myVariable);
return false;
});
var c = $("<div class='Line1' id='Line1Software'></div>");
$("#ButtonDiv").append(c);
var r = $("<button class='waves-effect waves-light btn-large btnSearch Line1' id='Software' draggable='true'>Software</button>");
$("#Line1Software").append(r);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="ButtonDiv">
</div>
Your question is a bit odd because you give yourself the answer... Look at your code, you are explicitly using event delegation:
$('#ButtonDiv').on('click', '.Line1', function () {
var myVariable = this.id;
});
This code means that, for each click on a .Line1 element, the event will be delegated to the #ButtonDiv element (thanks to bubbling).
If you do not want this behavior, just do that:
$('.Line1').on('click', function () {
var myVariable = this.id;
});
This is also correct:
$('.Line1').click(function () {
var myVariable = this.id;
});
Related
I have some dynamically created objects from a jade template which contain buttons. I would like to be able to get the object when the button inside it is clicked. Here is what I currently have
mixin ad(name,media,payout)
.box.box-primary
.box-header.with-border
h3.box-title=name
.box-body
img(src=media, style='width:130px;height:100px;')
p.text-muted.text-center="$"+payout
p.text-muted.text-center preview
.box-footer.text-right
button.btn.btn-primary(type='button',id="share",name="share",onclick='getSelf()') Share
and the jQuery
var getSelf = function() {
var clickedBtnID = $(this).parent();
alert('you clicked on button #' + clickedBtnID.name);
}
I know my jQuery is incorrect because It just prints "undefined" but how would I print the name?
Thanks.
As of now, this doesn't refer to the button element, it refers to window object.
You can pass the this reference to the function
button.btn.btn-primary(type='button',id="share",name="share",onclick='getSelf(this)')
Modify your function to accept the reference, which can be used later.
var getSelf = function(elem) {
var clickedBtnID = $(elem).parent();
alert('you clicked on button #' + clickedBtnID.name);
}
However I would recommend you to use unobtrusive event handler instead of ugly inline click handler(get rid of it).
$(function(){
$("#share").on('click', function(){
var clickedBtnID = $(this).parent();
alert('you clicked on button #' + clickedBtnID.name);
});
})
You can reference to the element which triggered the event using the event.target property. The event information is passed as the first parameter to the event handler.
Complete working code.
$('div').click(function(event){
console.log(event.target.id)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div1">div1</div>
<div id="div2">div2</div>
<div id="div3">div3</div>
<div id="div4">div4</div>
<div id="div5">div5</div>
I have input and it toggles a function if it's been changed. I also have table that is created dynamically. And each row in table has an addButton. So, the problem is that this alert toggles so many times so I change the input, but I need to toggle it only once. How to deal with it?
$('.inputsearchform').bind('input', function() {
var addButton = $(".fa.fa-plus");
addButton.click(function() {
alert("test");
});
});
I don't need to add click event to this button, but I need to get onclick() event from it. But this code is only working way, that I found. By the way, I need to get this event only if button is clicked, not every time that I change input.
Question How to check onclick event on button, that appears dynmically, when the input changes?
I tried to add onclick event <i class="fa fa-plus" onclick="addButtonF()">
and in js file: function addButtonF(){
alert("test");
}
but I have an error addButtonF is not defined.
A start would be to define click outside of input handler to prevent multiple click handler calls at each click of addButton
So, the problem is that this alert toggles so many times so I change
the input, but I need to toggle it only once.
Not clear from Question which element needs to be toggled once, or which function should only be called once ?
addButton appears only if I write something in input. I need to use
alert only if I click on this button, not every time that I change
input.
Use event delegation to attach event to dynamically created elements having className .fa.fa-plus
$(".inputsearchform").bind("input", function() {
// create dynamic element
$("<table class='fa fa-plus'>")
.html("<tr><td>"
+ $(".fa.fa-plus").length
+ "</td></tr>"
).appendTo("body");
});
$(document).on("click", ".fa.fa-plus", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
Substitute className for class which does not set className of element; use latest version of jQuery
$(".inputsearchform").bind("input", function() {
var div = document.getElementById("div");
var table = document.createElement("table");
div.appendChild(table);
var tr = document.createElement("tr");
table.appendChild(tr);
var td = tr.insertCell(0);
td.innerHTML = "test";
td.className = "try"
});
$(document).on("click", ".try", function() {
alert("test");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<input type="text" class="inputsearchform">
<div id="div"></div>
jsfiddle https://jsfiddle.net/1x8ja6qe/2/
I'm playing around with Javascript and created a class. On initializing the class, I add a button to a certain div and then add an event listener to that button for when it's clicked. What is happening though is that the function gets fired when the page loads, and not when the button is clicked. Here is my code:
function Photobank(){
this.photos;
this.addPhotoButton;
}
Photobank.prototype.init = function(){
var btn = document.createElement('button');
btn.id = "photoupload";
var t=document.createTextNode("ADD PHOTOS");
btn.appendChild(t);
this.addPhotoButton = btn;
var pb = document.getElementById('photobank');
pb.appendChild(this.addPhotoButton);
this.addPhotoButton.addEventListener("click", this.launchMediaManager(), false);
}
Photobank.prototype.launchMediaManager = function(){
alert("Launching Media Manager");
}
Am I doing something noticeably wrong?
You're calling the function rather than passing the function as an argument to addEventListener. Take the parentheses off the end of the function name:
this.addPhotoButton.addEventListener("click", this.launchMediaManager, false);
It is because you are invoking the function and setting its result as the handler to the click event, instead set the function reference as the handler.
this.addPhotoButton.addEventListener("click", this.launchMediaManager, false);
I want to get the span id in JavaScript following code always returning M26 but I want different values on different click M26 or M27:
function clickHandler() {
var xid= document.getElementsByTagName("span");
var xsp= xid[0].id;
alert(xsp);
}
}
<html>
<BODY LANGUAGE = "javascript" onClick = "clickHandler();">
<a href="javascript:void(0)"><u><b><span id=M26>2011-
2012</span></b></u></a>
<div id=c26 STYLE="display:none">
<a href="javascript:void(0)"><u><b><span id=M27>2012-
2013</span></b></u></a>
<div id=c27 STYLE="display:none">
</body>
</html>
The problem you are facing is that var xid= document.getElementsByTagName("span"); gets all spans on the page regardless of where you click.
To solve this problem you should just pass a reference to the clicked object within the function. For example:
<span id=M26 onclick="clickHandler(this);" >2011-2012</span>
Then in your javascript code:
function clickHandler(object) {
alert(object.id);
}
However it is a good idea to bind the events within javascript rather than inline in the html tags.
This article describes the different ways in which you can bind events to elements.
There are several ways to get the id of the element that has just been clicked:
Pass a reference to this to the handler:
onclick="handlerFunc(this);">
Or, better yet, pass the event object to the handler, this allows you to manipulate the event's behaviour, too:
onclick='handlerFunc(event);'>
//in JS:
function handlerFunc(e)
{
e = e || window.event;
var element = e.target || e.srcElement;
element.id;//<-- the target/source of the event (ie the element that was clicked)
if (e.preventDefault)
{//a couple of methods to manipulate the event
e.preventDefault();
e.stopPropagation();
}
e.returnValue = false;
e.cancelBubble = true;
}
You can use getAttribute() function for this...
function clickHandler() {
var xid= document.getElementsByTagName("span");
var xsp= xid[0].getAttribute('id');
alert(xsp);
}
<html>
<body LANGUAGE = "javascript" onload = "clickHandler();">
<a href="javascript:void(0)"><u><b><span id=M26>2011-
2012</span></b></u></a>
<div id=c26 STYLE="display:none">
<a href="javascript:void(0)"><u><b><span id=M27>2012-
2013</span></b></u></a>
<div id=c27 STYLE="display:none">
</body>
</html>
See working Demo
I have a <div> element that has a click event attached to it using the following code:
var id = "someId";
var elem = document.getElementById("elemId");
elem.addEventListener("click", function() { someFunction(id); }, false);
At a later point I copy the element and add it to another part of the DOM, but need to first remove the click event
var elem = document.getElementById("elemId");
elem.removeEventListener("click", ???? , false);
I'm not sure how to reference the listener and so far nothing I have tried has removed the event from the element.
Any ideas?
Move the anonymous click handler function out of the addEventListener call:
var id = "someId";
var elem = document.getElementById("elemId");
var elemEventHandler = function() { someFunction(id); };
elem.addEventListener("click", elemEventHandler , false);
after which you should be able to:
var elem = document.getElementById("elemId");
elem.removeEventListener("click", elemEventHandler , false);
The answer above is correct.
However, in case, someone is looking to remove the onclick function which is attached to a button like this for eg
<button type="button" onclick="submit()" id="tour-edit-save">Save</button>
In this case, to remove the onclick attached function, one will have to remove the attribute onclick and that would work perfectly fine.
Here is how you would remove using pure JavaScript
document.getElementById('tour-edit-save').removeAttribute('onclick');
Using jquery
$('#tour-edit-save').removeAttr('onclick');
Hope this helps someone who's looking for this answer.