so I am creating a website that has dynamically added content and I want to bind on click events to the list items. The problem is I have a list item within a list item and I can not seem to get the second one to work.
HTML
<ul id="users" class="grid">
<li>
<figure>
<img src="image source" alt="Title" />
<figcaption>
<div>
<h3>Title</h3>
<ol>
<li> <span>Additional Button</span> </li>
<li> <span>Additional Button</span> </li>
<li> <span>Additional Button</span> </li>
</ol>
</div>
</figcaption>
</figure>
</li>
</ul>
Here is the JS
$('ul#users').on("click", "li", function(e) {
console.log($(this));
});
$('.grid ol').on("click", "li", function(e) {
console.log($(this));
});
The first bind works without an issue but the second one is never called. Does anyone have an idea on how to get this to work. Please keep in mind that the LI elements are all dynamically created.
If all your li elements asre dynamically created, (ul.grid>li and ol>li) then your click handler to .grid ol > li must be assigned each time you create ol element in .grid>li.
Another way is try to change from:
$('.grid ol').on("click", "li", function(e) {
console.log($(this));
});
to:
$('.grid').on("click", "li>ol>li", function(e) {
console.log($(this));
});
P.S. if you dynamically create elements, then add handlers to them when they are created (if that allow application logic).
Simple rule to do events on dynamic content is to apply bind event on closest outer parent that is not generated dynamically.
Example:
$('.grid').on('click', 'ol>li', function(e){
console.log($(this));
});
Just basically bind event on your not-dynamically created parent and manipulate selector inside of .on() context.
Your selector isn't working, change it to something like this:
$('ol li').on("click", "li", function(e) {
console.log($(this));
});
Related
I know that similar questions are being asked (like here) but, being a jQuery noob, I still can not attach a click listener to an a element within a li where the whole ul.li.a is dynamically appended to the DOM like this.
<div id="users-col">
<!-- dynamically appended -->
<ul id="users-list">
<li>
<a class="user" id="Alice">Alice</a>
</li>
<li>
<a class="user" id="Bob">Bob</a>
</li>
</ul>
<!-- END dynamically appended -->
</div>
Here is a (one of the many) jQuery functions that I have tried:
$('#users-col ul.li.a').on('click', '.user', (function () {
console.log('user clicked:', this.id);
});
How can I fix this?
You need to bind the event on element that is available (not added dynamically)
$('#users-col').on('click', 'a.user', (function () {
console.log('user clicked:', this.id);
});
For reference, jQuery.on
in such case you must hook an event with parent of dynamically created children:
$('#users-col').on('click', 'a.user', (function () {
console.log('click bound');
});
For convenience sake and reuse, I leave the first field just directly tied to the document:
$(document).on('click', '.user', (function () {
console.log('user clicked:', this.id);
}));
<div id="users-col">
<!-- dynamically appended -->
<ul id="users-list">
<li>
<a class="user" id="Alice">Alice</a>
</li>
<li>
<a class="user" id="Bob">Bob</a>
</li>
</ul>
<!-- END dynamically appended -->
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
The listener is directly tied to the document vice the class, so now it is very easy to reuse this class dynamically across your entire document.
I have seen that the inline/html events like onclick, mouseover etc are being used less and less and it is advised to register events using Javascript.
I currently have some HTML like:
<ul id="supported-locations">
<li onclick="setLocationId(32);">Mexico</li>
<li onclick="setLocationId(35);">Mongolia</li>
</ul>
Which works fine but I want to now do this without the "onclick" in the HTML but still be able to retrieve the ID number.
The <li> elements are retrieved via AJAX while the user types into an input box it queries the database and retrieve the data without loading the page.
When the user clicks on one of the countries it will run the setLocationId function which just simply sets a hidden HTML form element with the ID of the selected country so I can use that once the form is submitted.
How do you register an event listener for these <li>'s when the countries and their ID's will always be different and changing depending on what the user types into the box?
Use a data attribute to hold the number. On the onclick event, read the attribute on the element that was clicked.
HTML:
<ul id="supported-locations">
<li data-code="32">Mexico</li>
<li data-code="35">Mongolia</li>
</ul>
JavaScript:
$("#supported-locations").on("click", "li", function() {
var li = $(this);
console.log(li.data("code"));
});
Example:
JSFiddle
<ul id="supported-locations">
<li data-id="32">Mexico</li>
<li data-id="35">Mongolia</li>
</ul>
in jQuery
$('#supported-locations').on('click','li',function(){
setLocationId($(this).data('id'));
})
<ul id="supported-locations">
<li data-id="32">Mexico</li>
<li data-id="35">Mongolia</li>
</ul>
jQuery(function(){
$('#supported-locations li').click(function(){
alert($(this).data('id'))
})
})
I recommend giving a class to the dynamically loaded elements, then use jquery .on(http://api.jquery.com/on/) method to register event listeneres to elements belonging to a class, even those that are dinamically loaded..
Then you could just read out the data stored in the element(in the form of data-something attributes).
<ul id="supported-locations>
<li id="32">Mexico</li>
<li id="35">Mongolia</li>
</ul>
//Jquery
$("#supported-locations > li").on('click',function(){
setLocationId($(this).attr('id'));
});
When you register your event, you still have the ability to use this, which is linked to the HTML element.
In other word, you still can do something like that
<li id="YOUR_ID">Mexico</li>
And get the id of the li tag
You can attach an event handler to the li:
<ul id="supported-locations">
<li id="location32">Mexico</li>
<li id="location35">Mongolia</li>
</ul>
$("#supported-locations li").click(function() {
alert($(this).attr("id"));
});
http://jsfiddle.net/puL95/
try this.
$("#supported-locations li").click(function() {
alert("me")
}
I can't seem to get my jQuery right to remove a div when I delete something
Code is:
<div class="amend_order" data-item_key="1367264719mz7">
<p>Home Made Ice Cream</p>
<p class="small_text">Pistachio</p>
<p>
<a class="edit_item ui-link" href="javascript:void(0);">Edit</a>
----
<a class="deleter ui-link" href="javascript:void(0);">Delete</a>
</p>
</div>
I have tried using
$(this).closest('div').remove();
unfortunately this does not work.
Basically there is a list of several divs and I just want them to disappear when clicked.
If your container divs are dynamically added, you need to use event delegation. Try this:
$("#container").on("click", ".amend_order .deleter", function () {
$(this).closest("div").remove();
});
DEMO: http://jsfiddle.net/m6jVP/
If they're added dynamically, then the event binding won't actually find any elements and therefore won't execute when they're clicked. This event handling runs for any elements inside of #container that match the selector .amend_order .deleter when they are clicked.
You can replace #container with a selector that matches a stable (static) element containing these divs you're targeting, using document if necessary.
HTML
<div class="amend_order" data-item_key="1367264719mz7">
<p>Home Made Ice Cream</p>
<p class="small_text">Pistachio</p>
<p>
<a class="edit_item ui-link" href="javascript:void(0);">Edit</a>
----
<a class="deleter ui-link" href="javascript:void(0);">Delete</a>
</p>
</div>
JS
$('.deleter').on('click', function(){
$(this).closest('div').remove();
})
Live sample http://jsfiddle.net/Ny346/
Try pointing to the div:
$('div.amend_order').click(function(){
$(this).remove();
});
or when clicking on the delete button:
$('a.deleter.ui-link').click(function(){
$(this).parent('div').remove();
});
Try this:
$('.deleter').on('click', function(){
$(this).parent().parent().remove;
})
Live Sample
I have a three a tags on a page. User can "select" only one.
Markup:
<div class="fl_near">
<span class="title">title</span>
<p>
<a id="filter_today" class="first_tb" style="display: block">
<span>text1</span>
</a>
<a id="filter_tomorrow">
<span>text2</span>
</a>
<a id="filter_afterTomorrow" class="last_tb selected" style="display: block">
<span>text3</span>
</a>
</p>
</div>
JS code:
$('.fl_near').find('a:not(.selected)').click(function () {
alert('1');
$('.fl_near').find('a').removeClass('selected');
$(this).addClass('selected');
});
This code not works properly. If I select first or second tag then all OK - style is switched, but alert shows anyway. If I select first then I can't select the last.
Where is a problem and why?
Thanks.
DEMO
Because you don't bind click handler to the last element.
Try
$('.fl_near a').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
The find filter runs only once - it is not listening for successive clicks. Use event delegation for this - that way the filter will be applied when the click occurs, not, as currently, when you bind the event.
$('.fl_near').on('click', 'a:not(.selected)', function (evt) {
alert(1);
$(this).addClass('selected').siblings('a').removeClass('selected');
});
Note also I've simplified your add/remove-class line.
As it is now, you're not binding the click event to the link that is selected from start.
I would change:
$('.fl_near').find('a:not(.selected)').click(function () {
to
$('.fl_near a').click(function () {
I have some list item tags in my jsp. Each list item has some elements inside, including a link ("a" tag) called delete. All that I want is to delete the entire list item when I click the link.
Here is the structure of my code:
$("a").click(function(event) {
event.preventDefault();
$(this).parent('.li').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li id="191" class="li">
<div class="text">Some text</div>
<h4>Text</h4>
<div class="details">
<img src="URL_image.jpg">
<span class="author">Some info</span>
<div class="info"> Text
<div class="msg-modification" display="inline" align="right">
<a name="delete" id="191" href="#">Delete</a>
</div>
</div>
</div>
</li>
But this doesn't work. I'm new at jQuery, so I tried some things, like for example:
$(this).remove();
This works, it deletes the link when clicked.
$("#221").remove();
This works, it deletes the indicated list item, but it's not "dynamic".
Can someone give me a tip?
Simply use the .closest() method: $(this).closest('.li').remove();
It starts with the current element and then climbs up the chain looking for a matching element and stops as soon as it found one.
.parent() only accesses the direct parent of the element, i.e. div.msg-modification which does not match .li. So it never reaches the element you are looking for.
Another solution besides .closest() (which checks the current element and then climbs up the chain) would be using .parents() - however, this would have the caveat that it does not stop as soon as it finds a matching element (and it doesn't check the current element but only parent elements). In your case it doesn't really matter but for what you are trying to do .closest() is the most appropriate method.
Another important thing:
NEVER use the same ID for more than one element. It's not allowed and causes very hard-to-debug problems. Remove the id="191" from the link and, if you need to access the ID in the click handler, use $(this).closest('.li').attr('id'). Actually it would be even cleaner if you used data-id="123" and then .data('id') instead of .attr('id') to access it (so your element ID does not need to resemble whatever ID the (database?) row has)
what about using unwrap()
<div class="parent">
<p class="child">
</p>
</div>
after using - $(".child").unwrap() - it will be;
<p class="child">
</p>
Use parents() instead of parent():
$("a").click(function(event) {
event.preventDefault();
$(this).parents('.li').remove();
});
Delete parent:
$(document).on("click", ".remove", function() {
$(this).parent().remove();
});
Delete all parents:
$(document).on("click", ".remove", function() {
$(this).parents().remove();
});
I have stumbled upon this problem for one hour. After an hour, I tried debugging and this helped:
$('.list').on('click', 'span', (e) => {
$(e.target).parent().remove();
});
HTML:
<ul class="list">
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
<li class="task">some text<span>X</span></li>
</ul>
You could also use this:
$(this)[0].parentNode.remove();
$('#' + catId).parent().remove('.subcatBtns');