My script:
$(document).ready(function(){
var folder = "/img/gallery/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("#galleryColumnOne").append( "<img src='"+ folder + val +"'>" );
$("#galleryColumnTwo").append( "<img src='"+ folder + val +"'>" );
}
});
}
});
});
html:
<body>
<div class="wrapGalleryList" id="galleryColumnOne"></div>
<div class="wrapGalleryList" id="galleryColumnTwo"></div>
</body>
Target: to load full set of images from the folder and display them in div like: pic1 in galleryColumnOne, pic2 in galleryColumnTwo, etc..
Current state: each div display complete full set of images.
Edit: current state of the script generate:
<div1> pic1, pic2, pic3, etc. ; <div2> pic1, pic2, pic3, etc.
should be:
<div1>pic1, pic3, pic5, etc. ; <div2> pic2, pic4, pic6, etc.
So, final working script for my problem (thanks to #cars10m)is:
<script>
$(document).ready(function(){
var folder = "/img/gallery/";
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("#galleryColumn"+(i%2?'One':'Two')).append( "<img src='"+ folder + val +"'>" );
}
});
}
});
});
</script>
As a simple fix you could change your success function to something like this:
function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
$("#galleryColumn"+(i%2?'One':'Two')).append( "<img src='"+ folder + val +"'>" );
}
});
Although this will not be the quickest way of doing it and it would get "out of sync", when there are <a> links in data that do not point to images.
A better solution would be
function (data) {
var imgs=[];
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
imgs.push(folder+val);
}
});
$("#galleryColumnOne").append( "<img src='"+imgs.filter((v,i)=>i%2).join("'><img src='")+"'>" );
$("#galleryColumnTwo").append( "<img src='"+imgs.filter((v,i)=>(i+1)%2).join("'><img src='")+"'>" );
}
My answer is not tested, therefore no guarantees. But the main idea is to get the .append() part out of the loop over the individual links. This way the (slow).append() function will only be called once for each div. The contents (an HTML string) is prepared by using a fast Array.filter() and .join() operation.
There is one further point I would like to remark upon: You are using the expression
$(data).find("a").attr("href", function (i, val) {...});
to loop over <a> elements in your data HTML string. It works, as you have confirmed. I was puzzled, why you used this function, as its primary purpose is to set the href attribute of each matched element. After having had a closer look at the jQuery .attr documentation it became clear to me that this is a valid way to directly access the chosen attribute value for all matched elements and do something with it. As long as the function does not return anything, the attribute will remain unchanged. However, the more conventional way of looping over DOM elements with jQuery would be:
$(data).find("a").each(function (i, elm) {...});
elm is the DOM element and you would get its href attribute with elm.href.
Related
I am adding query string to urls using this jQuery
$( 'a' ).attr( 'href', function(index, value) {
return value + '?appp=3';
});
This works fine, but after the ajax load, the new href's created are not recognized by the above jQuery. Is there a way to reload the code so to affect the new posts URL's which are loaded via ajax. Super thanks.
Perfect, thanks #developer, that worked nicely. Here how I did it as you mentioned:
function apendquery(){
$( 'a' ).attr( 'href', function(index, value) {
return value + '?appp=3';
});
};
$(document).ready(function(){
apendquery();
});
$(document).ajaxComplete(function () {
apendquery();
});
Of course it wont work on new elements. You can create function which you shuold call each time when new 'a' elements appears in DOM. Also you will need to create some kind of flag which helps you identify and update the href only for the new elements.
var updateHref = function(){
$( 'a[data-updated!=1]' ).attr( 'data-updated',1).attr( 'href',
function(index, value) {
return value + '?appp=3';
});
};
...
$.ajax(...)
.done(function() {
...
// add new 'a' tags
....
// then call our function to update href
updateHref();
});
Actually here is my final code which is better version in case the URL already appended a query should anyone might find useful:
function apendquery() {
$('a').attr('href', function(index, value) {
return value + (value.indexOf('?') !== -1 ? "&" : "?") + 'appp=3';
});
};
$(document).ajaxComplete(function() {
apendquery();
});
I have created an unordered list just like in this example - DirectionAwareHoverEffect .
Because I may have a lot of content, I decided to automate the markup. I included the content in a JSON file. The file is loaded using the following code.
$.ajax({
//cache: false,
url: "../content/"+"benefits.json",
dataType: "json",
success: function(data) {
var rows = data.rows;
var item = '<ul id="da-thumbs" class="da-thumbs">';
$.each(rows, function(idx, obj) {
item += '<li><a class="hvr-float"><img src="' + obj.image + '" /><div><span>' + obj.title + '</span></div></a></li>';
});
item += '</ul>';
$("#benefits-container").html(item);
}
});
However after having done so, the JS effect no longer works and I don't see any errors when I use the debugging tool.
The JS effect for the DirectionAwareHoverEffect (according to the tutorial) is done using this code
$('#da-thumbs > li ').each( function() {
$(this).hoverdir({
hoverDelay : 0
});
} );
Of course, this code calls its own library given in the source code.
I included the content loading function in the $(window).load() function and the JS effect in the $(document).ready() function. But I do not get any effect.
Any help will be much appreciated.
You either need to use delegation like on() or you need to call the plugin after the ajax call and the appending of the elements.
So, either, after this line
$("#benefits-container").html(item);
do
$('#da-thumbs > li ').each( function() {
$(this).hoverdir({
hoverDelay : 0
});
} );
or try and see if you can delegate like
$(document).on('hoverdir', '#da-thumbs > li', function(){
return {hoverDelay : 0}
}));
$('#da-thumbs > li ').each( function() {
} );
Note, above delegate suggestion may not be %100 correct as I am not sure how to bind to custom events(and can't look it up right now, sorry :) ).
I am using getJSON to access Vimeo's Simple API, and any objects created on the page by the call, do not react to the rest of the javascript that is on the page. It is probably something simple that I am missing. Here is my getJSON code:
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').prepend('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
});
});
Here you go: http://jsfiddle.net/8t3Xq/1/
This demonstrates loading your <li> thumbs just as your question does, then I show how to easily change one of them. How to "change" them is endless, this is just a simple example of changing the content and background. So you must not have your selectors right.
This is just a snippet, see fiddle for everything...
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').prepend('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
});
});
window.changeIt=function()
{
$('li').first().html("I'm changed!");
$('li').first().css("background-image","");
}
Just make sure the <li>s are present first before your code that changes them is present. Would need to see more of you code to understand when/how that happens.
$.getJSON("http://vimeo.com/api/v2/album/1822727/videos.json", function(data){
$.each(data, function (index, value) {
var videoID = value.id;
var videoThm = value.thumbnail_large;
$('#galThms').append('<li id="thm' + videoID + '" style="background-image:url(' + videoThm + ');"></li>');
console.log(videoThm);
$( "#galThms li" ).click(function() {
$(this).hide();
});
});
});
try this
there is no way that my answer is so far removed from the problem statement. my guess is that either I somehow errantly posted this answer or the problem was edited. apologies
you could also use:
$(document).on('click','li .playVideo',function(){
//do something
});
i would probably change your #playVideo to a class, if you will have multiple li's
I have a problem with displaying the id of the clicked div on the screen in an alert window. I am pretty confident this is because of the order of the controls and event handlers being added to the page, however after trying different ways I am unable to get this to work. Unfortunately I can't post reproducible code due to the div's being created from an ajax get request.
$(document).ready(function () {
$.getJSON('ClientPortal/GetSkills', function (data) {
var test = 'poo';
$.each(data, function (data) {
$('#flipContainer').append("<div class=flip id='" + this.Value + "' value='" + this.Value + "'>" + this.Text + "<//div>");
})
})
})
$(document).ready(function () {
$(".flip").on('click', function () {
alert($(this).attr("id"));
})
})
Try this :
$(document).ready(function () {
$("#flipContainer").on("click", ".flip", function () {
alert($(this).attr("id"));
})
})
You effectively have to base you click-binding on an element existing when the DOM ready event fires... But with this syntax, you delegate the binding on an existing element but it applies to another element contain in the first one...
See the jQuery documentation for on (for line "selector") : http://api.jquery.com/on/#on-events-selector-data-handlereventObject .
I have a blank div called "content". Links are later added to "content" using jquery append. Using empty() does not work; I am guessing empty() wont clear the links added by jquery because the links are not added to the DOM?
function should clear, then display new links, but its not clearing the links, just appending to whatever was present.
function getSubRedditLinks(url)
{
$("#content").empty(); //doesnt work
$.getJSON(
url + suffix,
function foo(data)
{
$("#content").empty(); //doesnt work
$.each(
data.data.children,
function (i, post)
{
$("#content").append( '<section>' +
'' + post.data.title + '' +
'</section>' );
}
);
}
);
$("#content").empty(); //doesnt work
}
Function is called like this:
<li><a class="link" href="#" onclick=getLinks("localhost")>Blogroll</a></li>
Apparently, empty() should work. I simplified my code above, put its not working in the 3 places I put them. It just keeps adding links to the #content
Try this out:
function getLinks(url)
{
$.getJSON(
url + suffix,
function(data)
{
var items = [];
$.each(
data.data.children,
function (i, post)
{
var section = $('<section></section>').append('<a></a>');
section.find('a').attr('href', '#post=post-' + i).text(post.data.title);
items.push(section[0].outerHTML);
}
);
$('#content').empty().append(items.join(''));
});
}
Use $(...).remove() instead... Or $("#content").html("")
Works for me, check this out
http://jsfiddle.net/gzNFK/2/
note: remove the comment to use it