submit <button> doesn't work after an explode before it - javascript

I've looked through stackoverflow for days, and none of the stuff I worked. Anyways, after an explosion and appending a submit button to my document the button doesn't alert when clicked.
$(document).ready(function() {
alert('hi');
$("#a").click(function() {
$(".main, .topbar, button").toggle("explode");
$('body').delay(8100).append("<img src='picture.png'> <form > <input type='text'></form><button id='submit'>submit</button>");
});
$("#submit").click(function() {
alert('hi');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='a'>button</button>
Any suggestions?

You are binding click to submit before submit is even added to htmlDOM. To do it that way you have to first add submit to htmlDOM and then bind the event handler.
But, for such dynamic elements you can use jQuery on function and delegate from any parent element. It is not recommended to delegate from body, you can delegate from nearest parent that is present during document.ready event.
$(document).ready(function() {
alert('hi');
$("#a").click(function() {
$(".main, .topbar, button").toggle("explode");
$('body').delay(8100).append("<img src='picture.png'> <form > <input type='text'></form><button id='submit'>submit</button>");
});
$("body").on('click','#submit',function() {
alert('hi');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id='a'>button</button>

I'm not 100% if I understood what you're trying to do there but check if this works:
<script>
$(document).ready(function () {
alert('hi')
$("#a").click(function () {
$(".main, .topbar, button").toggle("explode");
$('body').delay(8100).append("<img src='img.png'> <form > <input type='text'><button id='submit'>submit</button></form>");
});
$("#submit").click(function () {
alert('hi');
});
});
</script>

I assume you are inserting the button after page load, but calling the click handler before the element is on the page. Therefore jQuery can't find your element.
If you want to assign your click handler on page load, that's fine. Just assign your click handler to any parent element that is on the page when the page loads, like <body> and then using the jQuery .on() method to specify a descendant selector like so :
$('body').on('click', '#submit', function(){ alert('hi'); });

Related

How to call a function when a div is dynamically generated using jQuery

The scenario I want to achieve is as follow:
$("#parentDiv").on("load",'#childDiv', function () {
// do something...
});
I would like to call a function when a child div is dynamically generated and shown on the page, but there is no suitable event that can achieve this. Any hint or help would be appreciated.
Instead of load, you can make use of a custom event which gets triggered with .trigger():
$(document).ready(function() {
$("button").on("click", function() {
$("body").append("<div id='new'>Created</div>").trigger('custom-event');
});
});
$(document).on("custom-event", function() {
console.log('DIV created!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<button>Create element</button>
</body>

jquery (hover and load) events binding on dynamically created elements

I am able to bind click event to element with class name keybox. And this element is generated dynamically.
$('body').on('click','.keybox', function(){
// some code here
});
But for same element I tried binding hover and load event using following code:
$('body').on('hover','.keybox', function(){
// some code here
});
$('body').on('load','.keybox', function(){
// some code here
});
....and its not working as expected.
Can someone help with this problem? I want to bind hover and load event to my element with class name keybox and this element is generated dynamically.
Instead of hover, use mouseenter and mouseleave event. Instead of body.load use
$(document).ready(function() {
You can use following approach to bind multiple events and get object information via event object.
$('body').bind('click hover load', '.keybox', function(e){
if ( e.type === 'hover') {
// do something
}
else if(e.type === 'click') {
// do something
}
....
});
Make sure you bind events in $(document).ready(function() {} or load javascript just in bottom of html document body.
Since hover is deprecated you should use mouseenter and mouseleave for load you can write using event using on(load is equivalent to ready).
$(function(){
$(document).on('mouseenter', '.keybox', function () {
$(this).css('color','red');
});
$(document).on('mouseleave', '.keybox', function () {
$(this).css('color','black');
});
$(document).on('click', '.keybox', function () {// click on dynamically loaded events.
$(this).css('color','green');
});
$('#btn').click(function() {
$('#parent').append("<div class='keybox'>sample1</div>");
$('#parent').append("<div class='keybox'>sample2</div>");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parent">
zdhsdhsau
</div>
<input type="button" id="btn" value="create"/>

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
}

jQuery getting data attribute not working

I have a script that produces a number of buttons with a class and I want it to alert the data attribute on click but it's not working.
Here is the output of HTML
<button class="request box-button" data-value="18492500814">Request</button>
jQuery code
$(document).ready(function(){
$('.request').each(function () {
var photoID = $(this);
photoID.click(function () {
alert($(this).data('value'));
});
});
});
Since your elements don't exist when the page loads, the event won't be bound to them. Fix that by using event delegation:
$(document).ready(function(){
$(document).on('click','.request', function () {
alert($(this).data('value'));
});
});
JS Fiddle demo with dynamically generated elements
Note: Here, I used $(document).on() because I don't have your page's structure. But if you insert the buttons in a container that already exists in your HTML, use this instead: $('#myContainer').on(). It won't be noticeable, but it is best for performance.
Why not just have the listener on request, instead of inside of the loop. Also use the attr to get the data-value
$(document).ready(function(){
$('.request').click(function () {
alert($(this).attr('data-value'));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button class="request box-button" data-value="18492500814">Request</button>
Try with attr method.
$(document).ready(function(){
$('.request').each(function () {
var photoID = $(this);
photoID.click(function () {
alert($(this).attr('data-value'));
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<button class="request box-button" data-value="18492500814">Request</button>

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>

Categories