Create clone on another function with jquery - javascript

It shows a message 'Hi' when I click on 'ShoW',
But when I click on the next option 'ShoW', it does not show a message.
$('.btn').on("click", function () {
alert('Hi');
$('.box .btn').remove();
$('.btn').clone().appendTo('.box');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">ShoW</div>
<div class="box"></div>
What code should I add for JS?

This is because the event handler you created is bound to objects that existed when it was created:
$('.btn').on("click", function () {
This will only work for .btn elements that were already available at the time this line of code ran - it is not evaluated by jQuery again.
Instead, use this format for binding the event, which will pick up dynamically created elements:
$(document).on('click', '.btn', function () {
Seen here in this working snippet:
$(document).on('click', '.btn', function () {
alert('Hi');
$('.box .btn').remove();
$('.btn').clone().appendTo('.box');
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="btn">ShoW</div>
<div class="box"></div>

You have to set event once more again after clone.
then, you can declare your event callback as a function, and set event again after cloning on the cloned element, like this:
function appendShowButton() {
alert('Hi');
$('.box .btn').remove();
var newEl = $('.btn').clone().appendTo('.box');
newEl.on('click', appendShowButton);
return false;
}
$('.btn').on("click", appendShowButton);

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>

Javascript event triggering creating multiple button .on('click)

I'm using HTML slim for the code below.
.page
.paper
button.button.js-copier I copy things
- content_for :js_includes do
javascript:
var startingHtml = $('.page').html();
function initializePlugin() {
$('.js-copier').each(function () {
$(this).on('click', function () {
$('.page').append(startingHtml);
$(document).trigger('page-refreshed');
});
});
}
// Run it right away
initializePlugin();
$(document).on('page-refreshed', initializePlugin);
Is there a way to fix the fact that when I click on the "I copy things" button, it creates multiple copies of the button as it is iterating over all the button from the button that was selected?
Also, is there a better way to write this code. All I'm trying to do is duplicate the button anytime I click on any buttons(first and any new button created buttons)
-Anthony
First change this:
$('.js-copier').each(function () {
$(this).on('click', function () {
...
to this:
$('.page').on('click', '.js-copier', function () {
...
Read this to understand https://learn.jquery.com/events/event-delegation/#event-propagation
Then remove the 'page-refreshed' event because you don't need it:
$(document).trigger('page-refreshed');
...
$(document).on('page-refreshed', initializePlugin);
Demo solution:
var startingHtml = $('.page').html();
function initializePlugin() {
$('.page').on('click', '.js-copier', function () {
$('.page').append(startingHtml);
});
}
// Run it right away
initializePlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page">
<div class="paper">
<button class="button js-copier"> I copy things</button>
</div>
</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
}

Add more code to inherited event with jQuery

I have an inherited jQuery code where the scroll event has been set:
$(window).on('scroll', function(event) {
// Whatever
});
Now I need to add some more functionality to the previous code when a click event is fired, but this new code must be removed when another element is clicked, something similar to the below code:
$('#element1').on('click', function(){
$(window).on('scroll', function(event) {
// Add my code to the inherited one
});
});
$('#element2').on('click', function(){
$(window).on('scroll', function(event) {
// Unbind my code and leave the original behaviour
});
});
However, I cannot rewrite the inherited code. Is there any way to achieve this?
Thank you very much in advance
You can use event.namespace to bind the event. then you can use .off() to remove an event handler using namespace
$('#element1').on('click', function(){
$(window).off('scroll.element').on('scroll.element', function(event) {
// Add my code to the inherited one
});
});
$('#element2').on('click', function(){
$(window).off('scroll.element');
});
Using the above approach, default scroll event handler will have no impact.
Instead of binding scroll event to body you can bind it to body specific class. Clicking button will swap classes.
$(document).ready(function() {
$('.btn').click(function() {
$('.body')
.removeClass($(this).data('passive-class'))
.addClass($(this).data('active-class'));
});
});
.origin {
color: red;
}
.custom {
color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="body">
Some content
<button class="btn" data-active-class="origin" data-passive-class="custom">Scroll origin</button>
<button class="btn" data-active-class="custom" data-passive-class="origin">Scroll custom</button>
</div>
Place all code inside function and use flag to execute as needed.
var additionalCode = false;
function usefulCode(event) {
// here is your default code
if (additionalCode) {
// here is additional code
}
}
$(window).on('scroll', usefulCode);
$('#element1').on('click', function(){
additionalCode = true;
});
$('#element2').on('click', function(){
additionalCode = false;
});

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>

Categories