jquery trigger click in a loop - php

Hi I am trying to append facebook friends thumbnail in list item and add trigger on each of them. but now it trigger the click but it's only getting fbid of the last appended item inside the click callback. How can I attach click event on each of them correctly?
for(var i=0;i<obj.photo.length;i++) {
var img=$('<img src="https://graph.facebook.com/'+obj.photo[i]['fb_id']+'/picture" />');
var anchor=$('');
var li = $('<li></li>');
var fbul = $('#fb_friends');
anchor.append(img);
li.append(anchor);
fbul.append(li);
anchor.click(function(){
alert(anchor.attr('id'));
});
}

the problem is because, you are using a closure variable anchor inside your callback function for click event. The solution to this problem is to fetch the clicked element from the event properties as given below. Inside the event handler method this points to the element to which the handler is registered to.
anchor.click(function() {
var $this = $(this);
alert($this.attr('id'));
});
But since you are working with dynamic element I recommend using event delegation with .on()
var fbul = $('#fb_friends');
fbul.on('click', 'a', function() {
var $this = $(this);
alert($this.attr('id'));
})
for (var i = 0; i < obj.photo.length; i++) {
var img = $('<img src="https://graph.facebook.com/' + obj.photo[i]['fb_id']
+ '/picture" />');
var anchor = $('');
var li = $('<li></li>');
anchor.append(img);
li.append(anchor);
fbul.append(li);
}

Related

How to add extra space to div using Jquery?

I am working on the sticky menu and highlight menu based on div id in WordPress. I have completed code well but I got a problem.
I have a sticky header when I click menu item in side sticky menu title going back to header title not visible.
I want result like this.'
How can I solve this?
My Jquery Code
jQuery(function($) {
/**
* This part causes smooth scrolling using scrollto.js
* We target all a tags inside the nav, and apply the scrollto.js to it.
*/
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, this.hash);
});
var aChildren = jQuery("#nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = jQuery(aChild).attr('href');
console.log(ahref);
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop()+70; // get the offset of the window from the top of page
console.log('Window Position:'+windowPos);
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
//console.log(theID);
var divPos = $(theID).offset().top-150; // get the offset of the div from the top of page
console.log('Div Position:'+divPos);
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("nav-active");
} else {
$("a[href='" + theID + "']").removeClass("nav-active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("#nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("#nav li:last-child a").addClass("nav-active");
}
}
});
});
You need to offset the height of the heading when you jump to an anchored section.
Are you using the jQuery scrollTo plugin? If you can do something like:
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, 800, {offset: {top:-80, left:0} });
});
Options for scrollTo found here: http://demos.flesler.com/jquery/scrollTo/

Cannot apply jquery delegate to a dinamically generated element

Hello I'm trying to call to a function when one make a click on some elements.
I'm doing a form using symfony php framework. Following this:
http://symfony.com/doc/current/cookbook/form/form_collections.html#template-modifications
I readed this:
https://stackoverflow.com/a/1207393/4386551
But it does not work with a.delete elements, it works for a.add only.
var $collectionHolder;
// setup an "add a tag" link
var $addTagLink = $('Add a tag');
var $newLinkLi = $('<li></li>').append($addTagLink);
jQuery(document).ready(function() {
// Get the ul that holds the collection of tags
$collectionHolder = $('ul.details');
// add the "add a tag" anchor and li to the tags ul
$collectionHolder.append($newLinkLi);
// count the current form inputs we have (e.g. 2), use that as the new
// index when inserting a new item (e.g. 2)
$collectionHolder.data('index', $collectionHolder.find(':input').length);
$addTagLink.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// add a new tag form (see next code block)
addTagForm($collectionHolder, $newLinkLi);
});
$(".details").on("click", "a.add", function (){alert("HEY");});
$(".details").on("click", "a.delete", function (){alert("HEY");});
});
function addTagForm($collectionHolder, $newLinkLi) {
// Get the data-prototype explained earlier
var prototype = $collectionHolder.data('prototype');
// get the new index
var index = $collectionHolder.data('index');
// Replace '__name__' in the prototype's HTML to
// instead be a number based on how many items we have
var newForm = prototype.replace(/__name__/g, index);
// increase the index with one for the next item
$collectionHolder.data('index', index + 1);
// Display the form in the page in an li, before the "Add a tag" link li
var $newFormLi = $('<li></li>').append(newForm);
$newLinkLi.before($newFormLi);
addTagFormDeleteLink($newFormLi);
}
function addTagFormDeleteLink($tagFormLi) {
var $removeFormA = $('delete this tag');
$tagFormLi.append($removeFormA);
$removeFormA.on('click', function(e) {
// prevent the link from creating a "#" on the URL
e.preventDefault();
// remove the li for the tag form
$tagFormLi.remove();
//reload_total();
});
}
what's wrong with a.delete and jquery.on?
Try to change to:
$(".details a.add").on("click", function (){alert("HEY");});
$(".details a.delete").on("click", function (){alert("HEY");});
Or this:
$(".details").on("click", "a.add, a.delete", function (){alert("HEY");});

How to initialize href using jQuery

I'm trying to append my href attribute values by using the below code
$(document).ready(function() {
jQuery("#help_url").click(function(){
var href = $(this).attr('href');
alert(href);
var txt_api_key = $('#txt_api_key').val();
var txt_postcode = $('#txt_postcode').val();
var txt_countrycode = $('#txt_countrycode').val();
$('a#help_url').attr('href', href+txt_postcode+"/"+txt_countrycode+"?api_key="+txt_api_key);
});
});
This is working perfect. But the issue is after the first click the link will become http://api.fastway.org/v1/psc/pickuprf/2148/1?api_key=5340c900251a6105a19a58a1590472bb and on the next click after I changing the "txt_countrycode" value or if not chnaging any value it becomes http://api.fastway.org/v1/psc/pickuprf/2148/1?api_key=5340c900251a6105a19a58a1590472bb2148/1?api_key=5340c900251a6105a19a58a1590472bb
ie, again adding "href+txt_postcode+"/"+txt_countrycode+"?api_key="+txt_api_key"
How can I solve this?
One easy solution is to read the value of the href in dom ready and use it in the click handler, so that the href will have a non updated value
$(document).ready(function () {
var href = jQuery('#help_url').attr('href');
jQuery("#help_url").click(function () {
alert(href);
var txt_api_key = $('#txt_api_key').val();
var txt_postcode = $('#txt_postcode').val();
var txt_countrycode = $('#txt_countrycode').val();
$('a#help_url').attr('href', href + txt_postcode + "/" + txt_countrycode + "?api_key=" + txt_api_key);
});
});
When you click the button the click event will call .
the click event function have concatenation with existing url.So the existing url is append with country code

Jquery selector not working after append

I have a php script that I call that returns html in a way that it can be directly inserted into a container or the body and just work (E.X. '<image id="trolleyLogoEdge" class="pictureFrame party" src="tipsyTrixy.png" >'). After appending this text to a div the selector $('#pictureFrame > img:first') won't work. I'm not using event handlers or anything so I don't know why I'm having an issue. My code worked fine when I just had the image tags in the div without any manipulation so I'm assuming it must be a selector issue. I have tested my php output and it is exactly matching the html that was in the div before I decided to dynamically populate the div.
var classType = '';
var classTypePrev = '';
var width = $(window).width();
var height = $(window).height();
var size = (height + width)/2;
var time = 0;
$( document ).ready(function()
{
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
startSlideshow($('#pictureFrame > img:first'));
});
});
window.onresize = function()
{
width = $(window).width();
};
function startSlideshow(myobj)
{
classType = $(myobj).attr('class').split(' ')[1];
if(classTypePrev != classType)
{
$('.picDescription').animate({'opacity': "0"},{duration: 2000,complete: function() {}});
$('.picDescription.' + classType).animate({'opacity': "1"},{duration: 3000,complete: function() {}});
}
classTypePrev = classType;
myobj.animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) - 150), opacity: '1'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function() {}}).delay(2000).animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) + 150), opacity: '0'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function()
{
$(myobj).css("left", "100%");
}
});
setTimeout(function()
{
var next = $(myobj).next();
if (!next.length)
{
next = myobj.siblings().first();
}
startSlideshow(next)},9000);
}
Your code that appends the data to the frame has a typo in the ID selector.
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
^^here
startSlideshow($('#pictureFrame > img:first'));
});
It should probably be
$('#pictureFrame').append(data);
.find() gets the descendants of each element in the current set of matched elements.
> selects all direct child elements specified by "child" of elements specified by "parent".
Try:
startSlideshow($("#pictureFrame").find("img:first"));
If img is not direct child of #pictureFrame, .find() should work.
You should know the difference between
Delegated Event
Direct Event
check this for the difference between direct and delegated events.
If we were to click our newly added item, nothing would happen. This is because of the directly bound event handler that we attached previously. Direct events are only attached to elements at the time the .on() method is called. In this case, since our new anchor did not exist when .on() was called, it does not get the event handler.
check this link to official JQuery Document for further clarification.

Fetch variable in javascript from a link

I am trying to get a PHP variable to send through javascript and I am having trouble. I am using a jQuery popup I found online and when a user clicks an item, I need that item_id variable to be fetchable in the popup where I want to add a form.
My PHP section.
<a href="#?w=500&item_id='.$stock['id'].'" rel="popup1" class="poplight">
and the Javascript.
$(document).ready(function(){
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
var itemID = dim[0].split('=')[2]; //Gets the second query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="/layout/close_pop.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
document.getElementById('popup1').innerHtml = itemID;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
I added what I thought you work, but it does not var itemID = dim[0].split('=')[2]; //Gets the second query string value and document.getElementById('popup1').innerHtml = itemID;
Use a sophisticated function to retrieve URL query parameters:
function getParameterByName(name, locationObject)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(locationObject.search);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
[Adopted from here]
Simply call it like so:
getParameterByName('item_id', someLink);
Working Fiddle: http://jsfiddle.net/ADpYT/
You have a simple oversight in your original code ..
When you obtain your dim variable, you get an array with 2 items split at & . In the above code you get ["w=500", "item_id=some_value"] .So in order to get the itemID you have to use dim[1].
var itemID=dim[1].split('=')[1];

Categories