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
Related
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.
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 :) ).
So this little script was working exactly how i wanted it to but i did something to mess it up, basically i have one jQuery function
function loadDiv(id, page) {
$(function () {
$("#" + id).load(page);
});
}
and then this HTML (obviously through a for loop)
Edit this Post -->
I have tried removing "javascript:" I actually tried that because I could think of nothing else wrong.
I'm not sure but I don't think you need the extra jQuery wrapper.
function loadDiv(id, page) {
$(function () { // what is this line for?
$("#" + id).load(page);
});
}
I would just keep:
function loadDiv(id, page) {
$("#" + id).load(page);
});
I would write your links like so
Edit this Post
Then write your function like so
$('body').on('click', '.loadTrigger', function(){
var id = $(this).attr('data-id');
var page = $(this).attr('data-page');
$("#" + id).load(page);
});
I'm wondering how is possible to call a function with parameters inside a method.
I have 2 functions and i'd like to call function deleteCode() when clicked on list element which is created by addCode() function.
I'm sure the solution is really simple, but i just can't see it right now.
Many thanks!
function addCode(code) {
$('#codeList').append('<li class="codeList" onClick="deleteCode(code);">' + code + '</li>');
}
function deleteCode(code) {
$('#'+code).remove();
}
Do it unobtrusive and you're fine.
function addCode(code) {
$('#codeList').append($('<li>', {
'class': 'codeList',
'text': code,
'click': function(e) {
deleteCode(code);
}
}));
}
Ref.: $()
Create the <li> element via code rather than appending raw HTML.
function addCode(code) {
// Create the <li>
var newEl = document.createElement("li");
newEl.className = "codeList";
// Assign the click function via jquery's event helper.
$(newEl).click(function(code) {
// Call your deleteCode function and pass in the given parameter.
deleteCode(code);
});
// Append the new element to the codeList node.
$(#codeList).append(newEl);
}
You can try:
function addCode(code) {
$('#codeList').append('<li class="codeList" onClick="deleteCode(' + code + ');">'+code+'</li>');
}
You can do that like this:
function addCode(code) {
$('<li class="codeList">' + code + '</li>').click(function() {
deleteCode(code);
}).appendTo('#codeList');
}
function deleteCode(code) {
$('#'+code).remove();
}
...or more simply:
function addCode(code) {
$('<li class="codeList">' + code + '</li>').click(function() {
$('#'+code).remove();
}).appendTo('#codeList');
}
When using a library like jQuery (or even when not, frankly), there's virtually never any reason to use the old-style onclick attributes for setting up handlers. In the above, I've replaced it with the click function, which sets up a handler when the user clicks the element.
Note: Lazarus notes that your code is removing an element by id using the code value:
$('#' + code).remove();
...but that the code doesn't produce an element with that ID. I assume you've added that element with some other code elsewhere, and that the goal isn't to remove the li you've added with this code.
If you did want to remove that same li on click, no need for an ID at all:
function addCode(code) {
$('<li class="codeList">' + code + '</li>').click(function() {
$(this).remove(); // <== Changed here
}).appendTo('#codeList');
}