Find $(this) when using jQuery on with dynamically created elements - ajax

Lets say I have a list where the li are created dynamically, via AJAX :
​<ul id="demo-list">
<li data-test="test1" >Test 1</li>
<li data-test="test2" >Test 2</li>
<li data-test="test3" >Test 3</li>
</ul>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
When one of the li is clicked, I want to get the data attribute test of that particular li.
I tried something like :
$('#demo-list').on('click', 'li', function() {
console.log($(this).find('li').data('test'));
});
But it obviously gets all the list items and not just the particular one where the event happens.
Also, I know how to do this with .live(), but my question is how to do it via .on()

You have to remove the find from after your $(this) call:
$('#demo-list').on('click', 'li', function() {
console.log($(this).data('test'));
})
You can find the working example bellow:
http://jsfiddle.net/P356B/2/
EDIT:
if you have a widget/plugin that generates that content perhaps you could just attach the click event handler in the plugin. or have a construct such as:
(function($){
$(function(){
$('#demo-list').on('click', 'li', function() {
console.log($(this).data('test'));
})
});
})(jQuery)

I don't think you want find. Just do
console.log($(this).data('test'));

Try to do this :
console.log($(this).data('test'));
check here : http://jsfiddle.net/wDzkW/4/

Related

How to access html value of property that triggers an event in Meteor?

If I have a list of items in my template, like this:
<template name="myTemplate">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</template>
And my event handler looks something like this:
Template.myTemplate.events({
'click li': function(event) {
console.log(event.currentTarget//.? .html, .value?
}
});
How would I access the value of the li item that was clicked? i.e. I want to access 'One' or 'Two', etc. I tried .html and .value, which would have been the jquery-esque way to do it. My understanding is using 'currentTarget' is correct, since 'target' should match all li's, but I don't know how to hone in on the html value.
.innerHTML is the answer.
console.log(event.currentTarget.innerHTML); // Outputs li HTML content
As anonymous say. use the native attribute innerHTML to get the content of a DOM element.
otherwise Meteor come with JQuery so you can use it like this
console.log($(event.currentTarget).html());
You can try this :
Template.myTemplate.events({
'click li': function(event) {
$(event.target).html()
//console.log(event.currentTarget//.? .html, .value?
}
});

Infinite Scroll on ajax loaded content

I'm doing a WP_Query on let's say page-a.php, that page has a div called target where page-b.php is being loaded into. Page-a is a custom template and page-b is an archive page.
The structure on page A as example:
<body>
<div id="wrap">
<div class="target">
while
<div class="post">
<h1>Title</h1>
<p>Description</p>
</div>
endwhile
<div class="pagination"></div>
</div>
</div>
</body>
On page-b I only include the < post > and < pagination > divs within a regular wp loop.
Now the jQuery:
$(window).load(function() {
$('.target').infinitescroll({
navSelector : ".navigation",
// selector for the paged navigation (it will be hidden)
nextSelector : ".navigation a.next",
// selector for the NEXT link (to page 2)
itemSelector : ".post",
// selector for all items you'll retrieve
debug : true,
loading: {
finishedMsg: '<div class="alert alert-info" style="margin-top:50px"><p class="center">All posts were loaded</p></div>',
img: '',
msg: null,
msgText: "<p style='text-align:center; margin-top:50px;'><i style='font-size:60px; color:#babfc8'class='fa fa-cog fa-spin'></i></p>"
}
}, function(arrayOfNewElems){
$('.post').animate({"opacity":"1","max-height":"150px","padding":"15px 8px"},800, "jswing");
}
);
});
-If I call that script on page-a.php will only work on it, once page-b content is placed on
-If I call on page-a.php and page-b.php it works on first, then when first ajax content is loaded and then (if I apply a new filter) it won't work.
-If I call the script on my ajax response function it will work once, then if I apply another filter and target div refreshes content, I get the
Uncaught TypeError: Cannot call method 'appendTo' of null
div classes called (.target and .post) are present on the page.
What the hell am I doing wrong here. Thanks.
PS: If you need to take a look at the real scripts let me know and I will provide.
I think you need this : http://www.247techblog.com/implement-infinite-scroll-functionality-wordpress-wp-ajax-function/
Just need to call a wp ajax function

Getting parent element with delegated event?

I am trying to get parent element's id after re-attaching click event to a list item's third a tag (Delete), after list item is added via ajax. The structure looks as follows:
<ul id="list">
<li id="list_23">
Title
Edit | Delete
</li>
<ul>
The javascript is:
$('#list li').on("click", 'a:nth-child(2)', function(event) {
event.preventDefault();
id = $(this).parent().parent().attr('id');
console.log( id );
});
I am trying to get the list items id (the "list_23"), when third a link is clicked, after element is added via ajax.
That isn't the proper way to write delegated events with .on(). Try the following instead:
$('#list').on('click', 'li a:nth-child(3)', function(event) {
event.preventDefault();
id = $(this).parent().attr('id');
console.log( id );
});
See specifically this section of the .on() documentation for jQuery.
Edit: Updated my answer based on the li item being the element dynamically added to the DOM.
Edit 2: The problem was the :nth-child(n) selector is not zero index-based, rather it is one indexed based. Added working JSFiddle.
JSFiddle: http://jsfiddle.net/wyze/vTkYf/

How to get $(this) within a function declared in href of an anchor tag

I have the following anchor tag in a td in my table:
edit
I would like to find the parents of this td within my editAccount() function, doing the following:
function editAccount(){ console.log($(this).parent().parent()); }
However, I keep getting null in my console
You need pass the element under question
<a onclick="editAccount(this)" class="edit">edit</a>
and
function editAccount(elem){ console.log($(elem).parent().parent()); }
or using function.call.
<a onclick="editAccount.call(this)" class="edit">edit</a>
and
function editAccount(){ console.log($(this).parent().parent()); }
Using Jquery to bind the event.
<a class="edit" href="#">edit</a>
and
$(function(){
$('.edit').click(function(e){
e.preventDefault();
console.log($(this).parent().parent());
});
});
Fiddle
this does not refer to anything in that function.
Just add an actual event to the anchor:
$('.edit').on('click', function(){
console.log($(this).parent().parent());
return false;
});
Instead of using href="javascript:editAccount(), bind editAccount using standard event registration via jQuery:
$(".edit").on("click", editAccount);
You can also use an anonymous function instead of defining editAccount separately.
In case the .edit links are added dynamically, you can use event delegation:
$(document).on("click", ".edit", function (e) {
//prevent following the link if you want
e.preventDefault();
console.log($(this).closest("td"));
});

Why does my cycle slideshow hide all the slides?

The jQuery plugin cycle looks for elements of class slideshow. I want to add this class to a <ul> element to make a slideshow out of its <li>s. But when I add the slideshow class to the <ul> element, all <li> disappear and I get no slideshow whatsoever.
The HTML looks like this:
<ul>
<li>
<h3 class="expander">...</h3>
<div class="content">
<p>...</p>
<h4>...</h4>
<ul class="slideshow">
<li>...</li>
<li>...</li>
</ul>
</div>
</li>
...
</ul>
As you see, the slideshow <ul> is included in another list. This parent list consists of headers which reveal the content of each list item on click. I am hiding all the .contents programmatically when the DOM is ready. Then, I add a click listener to the .expanders so they can show the hidden .contents.
It is inside these .contentss that I have .slideshows which use the cycle plugin to cycle through their list items.
The other weird thing about all this is that the slideshow's worked perfectly before I transformed my headers into toggles for their associated content. Indeed, when I added the toggle functionality to the headers, the slides are no longer visible. But then if I take away the slideshow class, they are visible again. Of course, they no longer have slideshow functionnality...
Here is the javascript for all this:
$(document).ready(function()
{
var expanders = $('.expander');
expanders.each(function()
{
$('.content', $(this).parent()).toggle();
$(this).click(function()
{
$('.content', $(this).parent()).toggle("blind", {"easing":"easeInOutCirc"}, "normal");
});
});
$('.slideshow').each(function() {
var parent = $(this).parent();
$(this).cycle(
{
fx: 'scrollHorz',
easing: 'easeInOutCirc',
timeout: 0,
nowrap: 1
});
});
});
Any idea what could be causing this problem?
Apparently, I needed to move the cycle code above the toggle code, like this:
$(document).ready(function()
{
$('.slideshow').each(function() {
var parent = $(this).parent();
$(this).cycle(
{
fx: 'scrollHorz',
easing: 'easeInOutCirc',
timeout: 0,
nowrap: 1
});
});
var expanders = $('.expander');
expanders.each(function()
{
$('.content', $(this).parent()).toggle();
$(this).click(function()
{
$('.content', $(this).parent()).toggle("blind", {"easing":"easeInOutCirc"}, "normal");
});
});
});
I don't know why this works though, so better answers would be appreciated.

Resources