DOM only registering one click event remove element - javascript

I have a simple form, where I want to be able to remove DOM elements, that I might not need (eg. questions on a form).
This works only for the first element. After the first element is removed (clicked) it will be removed but then all further clicks are not registered.
The console will only display the first "click" as well.
I am using handlebars to generate some of the DOM elements in a loop, not sure if that would actually cause a issue, since I am able to see the elements in chrome inspector.
JS FUNCTION
let allItems = document.getElementById("main");
allItems.addEventListener("click",function(e){
console.log("click");
e.target.parentElement.remove();
e.preventDefault();
});
HTML -- HandleBars.
{{#each all}}
<div id="main">
<p class="delete">✘</p>
<span class="select">
<select>
<option value="0"></option>Selection</option>
</select>
</span>
</div>
{{/each}}

You've got two problems here:
you are assigning the same id to multiple elements, this is invalid html as id's are supposed to be unique.
This is a very common problem in javascript. the code only binds event listeners on the elements that were present in the page at the time the code ran. any newly added elements won't be present. the solution in this scenario is to remove the event listeners off the elements, and add a single listener on the document for click, then check the event target to see if it is one of the nodes you want.
I recommend to remove id of main from the elements, and give them all an identical class ie class="removable-form-item", then use a global click listener like so:
document.body.addEventListener('click',function(event){
if(event.target.classList.contains("removable-form-item")){
//got a click on our target name
// your code to remove the item here
e.target.parentElement.remove();
e.preventDefault();
}
});

Related

How to use click event on <a> tag

How to use click event on tag without id
Hello everybody, I have a html tag bellow:
<a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end fc-draggable fc-resizable" href="https://www.youtube.com/watch?v=XXXXX"><div class="fc-content"> <span class="fc-title">event</span></div><div class="fc-resizer fc-end-resizer"></div></a>
this html code was built automatically by jquery so I can't add id or "onlick" event on this tag.
What I want is when I click on this tag, it will open a new windows with href for me. I tried to use
$('.fc-day-grid-event).on('click, function() {
...//
});
But it's not working.
How should I do for this case? Please help.
this html code was built automatically by jquery so I can't add id or "onlick" event on this tag
If you can't control when that happens, you can still use event delegation to get involved in the click event:
$(document).on('click', '.fc-day-grid-event', function() {
...//
});
That works even if the code runs before the element exists. The code in your question only works if the element exists as of when your code runs. See the documentation for details.
As the code is generated after the page rendering, you should use a delegated event handler:
$('body').on('click','.fc-day-grid-event', function() {
//...
});
The original code is missing apostrophes after the class name and after the 'click'.
This should work:
> $('.fc-day-grid-event').on('click', function() {
...//
});
However you might consider to check, if there are other dom elements with that class. An ID is much safer. A workaround could be to use multiple classes in the jQuery selection by selecting the element(s), that matches them all:
$('.fc-day-grid-event.fc-h-event.fc-event.fc-start.fc-end.fc-draggable.fc-resizable')
but this might still be not sufficient, because these framework-classes seem to be dynamically created and maybe deleted and the selection might be too wide or too narow. You could try to select the a tag with parent/child relations, where you know, that you are getting the right element and you could even use the innerHTML of the elements. Alternatively you could iterate through a JQuery-Selection and check for certain attributes.
I'm not sure, if you want to change the target of the link or the target window of the link. Opening the target of a link in a new window works with standard html by using the target attribute
<a href='bla' target='_blank'>bla ...
If you use Javascript for manipulating the target adress of a link outside of the href, the code might get hard to maintain in most contexts and the user might get confused, because he get's to page, he didn't expect. I would try to manipulate the Javascript, that is creating the a tag or if that's really impossible, i would manipulate the existing a tag according to my needs and change the attributes like this, if you want to use jQuery:
For the target address of the link:
$('.fc-day-grid-event').attr("href", "www.newhrefvalue.com")
Or for opening the link in a new tab:
$('.fc-day-grid-event').attr("target", "_blank")
Then you don't need to prevent or emit events or create event listeners.
<a onclick="doStuff(this)">Click Me</a>

How to use JQuery.find() when DOM is dynamic

I have a cascading menu with the following flow;
click on an item from menu-1
creates and updates menu-2 li elements
click on an item from menu-2
creates and updates menu-3 li elements
etc..
```
$firstMenu = $('.prime-menu');
$secondtMenu = $('.second-menu');
$thirdMenu = $('.third-menu');
```
As i'm traversing through different elems. within each menu, using find() comes as a blessing, the issue is that the script loads when no menu other than the first menu is created so $secondtMenu.find('.item-year').click(function (clickEvent) {}) is 0 length.
What are my options in JQuery to make my find() functions work on elements that are not loaded yet in the DOM?
I thought of creating an event listener, but I think there are more terse approaches than that.
You should use delegates when dealing with dynamic HTML. For instance, use an outer element like document or body to "start" your finds.
$(document).find(".prime-menu");
EDIT: Find and event delegation
The solution was to use find with event delegation. Example event.
$(document).find(".prime-menu").on('mouseenter', '.track-table tbody tr', function(){ });
You state that when you click on an item from menu-1 it creates and updates menu-2 li elements. In this function is where you should do your event binding. The DOMElement will exist in js before being added to the dom, and that is where your bindings should be set.
If you need help share this code with us I'm sure myself or someone will be able to help you sort it out.
Bind the click handler to the menu parent, not the actual menu items.
Something like this might work...
$("#menuparent").on("click",".item-year",function(event) {
var clicked_element = event.currentTarget;
});
Doing it this way, even if the element with class .item-year is added to the dom after the click event is bound, it will still register the click.

jQuery click event does not fire on 'loaded' html

I'm trying to understand why loading HTML into a div block renders its class statement effectively non-existent to a click event.
My HTML code looks like this:
<div id="load-to"></div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
</div>
<button>load it!</button>
My JS code looks like this:
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$('.load-from-css').click(function(){
alert('clicked');
});
When I click the button the HTML from the lower div block is loaded into the upper div block, and then the HTML looks like this:
<div id="load-to">
<div class="load-from-css"> Hello!</div>
</div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
</div>
My question is, why does the second click event (defined in my jQuery code) only work on the original lower "Hello!" div block but not on the loaded upper one, when both have the same class definition?
Other answers have already covered the core reason for your problem (that copying the HTML of an element and placing it elsewhere will create a brand new DOM element and does not copy any events that were bound to the original element... keeping in mind that when you add an event listener, it will only bind to any elements that exist at the time that you do so)
However, I wanted to add some other options for accomplishing what you want to do.
jQuery has a few different techniques that make this sort of thing easy:
.clone() will essentially do the same thing as you are doing now*, it will copy the HTML content and create a new DOM element. However, if you pass true (ie: .clone(true)), it will clone it with all data and events intact.
* note that to truly get the same result as using .html(), you need to do .children().clone(), otherwise you'll get both the inner and outer div.. this may or may not be necessary depending on the use case
ex: https://jsfiddle.net/Lx0973gc/1/
Additionally, if you were in this same situation but did not want to make a clone, and simply wanted to move an element from one place to another, there is another method called .detach() which will remove the element from the DOM, but keep all data and events, allowing you to re-insert it later, in the same state.
ex: https://jsfiddle.net/Lx0973gc/2/ (not the best example because you won't see it move anywhere, but it's doing it!)
As another alternative, you can use delegated event binding, which actually binds the event to a different element (a parent) which you know won't change, but still allows you to target a child element within it:
$('body').on({
'click': function() {
alert('clicked');
}
}, '.load-from-css');
ex: https://jsfiddle.net/Lx0973gc/4/
The $('.load-from-css') finds all elements currently existing and .click(...) attaches a listener to all these elements. This is executed once.
Then you copy the raw html which does not transfer any listeners. The DOM has nodes onto which the listeners are attached but when you copy the plain HTML you essentially create new nodes based on the html.
Because you are copying just the HTML. The js file is loaded at the beginning, when there is just one instance of a div with the "load-from-css" class. You should execute again the code adding the listener after you copy the html. Somethinglike:
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
$('.load-from-css').click(function(){
alert('clicked');
});
});
#load-to inner HTML is initially empty. so added click listener only for #load-from .load-from-css. Dynamically bind element will not attach the click listener.
jQuery new version have the feature to attach the event for dynamic elements also. Try this
$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$(document).on('click', '.load-from-css', function(){
alert('clicked');
});
Also we can use like this
$( document ).delegate( "load-from-css", "click", function() {
alert( "Clicked!" ); // jQuery 1.4.3+
});
Simply because the page did not refresh. You loaded a content to another content without loading the page, and the browser wont recognized any event added to the loaded element.
What you should do is load your javascript tag with the load along with the content.
Your code should be like this:
<div id="load-to">
<div class="load-from-css"> Hello!</div>
</div>
<div id="load-from">
<div class="load-from-css"> Hello!</div>
<script>$('button').click(function(){
var html = $('#load-from').html();
$('#load-to').html(html);
});
$('.load-from-css').click(function(){
alert('clicked');
});</script>
</div>

How can I dynamicaly append elements outside the event handler with the help of an element created by this event handler?

I made the following code to clarify the question:
Html:
<body>
<div class="static">This is a static div</div>
<button class="add-dynamic-button">Click me to add a new button</button>
</body>
Js:
$(function(){
$('.add-dynamic-button').on("click",function(){
$('body').append("<button class='dynamic-button'>Click me to add a dynamic div'</button>");
});
$('.dynamic-button').on('click',function(){
$('body').append("<div class='dynamic-div'>This is a dynamic div</div>");
});
});
And here is jsfiddle to test: http://jsfiddle.net/6ZN5J/
When I have the $('.dynamic-button').on('click') handler inside the first click handler, a .dynamic-div is added fine.
But when I place it outside the first click handler scope (as in the example above), nothing happens. I initially thought that $.on works on any DOM element that is not yet created, but now it turns out that it works on new elements of the same class or type if they are already in the DOM or when $.on is placed inside the function that creates those elements.
Can you clarify why this happens and whether there are any methods to allow for using event handlers on dynamically created elements outside the handler they were created with?
Thanks
$() is a selector. It finds the element(s) that were in the document or the parent element from which you're peforming the whole query at the time you did it.
If you want further buttons bound to click event you'll need to manually bind them:
$('body').append("<button class='dynamic-button'>Click me to add a dynamic div'</button>")
.on("click", ....);

does jQuery's html() remove all data attached to elements that are replaced?

I'm displaying a tabbed interface with the help of jQuery. When you click a tab, a ajax call will replace all html from a $(".content") element with new html, using something like
$(".content").html(response);
When I do this, are all jquery events and functions that are attached to elements inside the .content div removed? Is it ok to fire these events and functions again after I replace the HTML ? If I click the tabs 324523452354 times, will it duplicate jQuery data every time?
Yes. They will be removed. You can use the live event to attach to elements that dont exist yet.
$(".myElementClass").live("click", function (e) {
e.preventDefault();
//do stuff
});
In this case, this function will always be called on myElement no matter when it is injected into the DOM.
All HTML inside of your selector is replaced with the parameter you pass in, implying it is completely removed from the DOM. Meaning if you have:
<div id="mine">
<ul>
<li>One thing</li>
</ul>
</div>
And I do a call as such:
$('div#mine').html("hey");
My HTML will then be:
<div id="mine">
hey
</div>
As you can see the is completely removed and all its bound events mean nothing. If you use the jQuery.live() binding instead however, then elements that don't yet exist can have events associated with them. Meaning if you add some elements to the DOM then they events will still work, without you have to rebind if you add more, or replace them.
**.live** events are binded at the document level , read the following document which is really useful
http://www.bennadel.com/blog/1751-jQuery-Live-Method-And-Event-Bubbling.htm

Categories

Resources