I wrote the following (part of a jQuery plugin) to insert a set of items from a JSON object into a <ul> element.
...
query: function() {
...
$.ajax({
url: fetchURL,
type: 'GET',
dataType: 'jsonp',
timeout: 5000,
error: function() { self.html("Network Error"); },
success: function(json) {
//Process JSON
$.each(json.results, function(i, item) {
$("<li></li>")
.html(mHTML)
.attr('id', "div_li"+i)
.attr('class', "divliclass")
.prependTo("#" + "div_ul");
$(slotname + "div_li" + i).hide();
$(slotname + "div_li" + i).show("slow")
}
}
});
}
});
},
...
Doing this maybe adding the <li> items one by one theoretically but when I load the page, everything shows up instantaneously. Instead, is there an efficient way to make them appear one by one more slowly? I'll explain with a small example: If I have 3 items, this code is making all the 3 items appear instantaneously (at least to my eyes). I want something like 1 fades in, then 2 fades in, then 3 (something like a newsticker perhaps). Anyone has a suggestion?
You might want to get the wanted effect by coding as following:
$(slotname + "div_li" + i).hide().delay(i*n).show("slow");
where n is some soft of delay modifier (in milliseconds); I assume i also here is the index, and thus a number.
Related
EDIT: data.item needed to be data.length , also had a missing var
I need to hide the 'Get More' button if the JSON success data is less than 9 items and then check new responses and make it visible again if it is more than 9. I'm not too familiar with jQuery. So far the " if(data.item < 9) " is very wrong and I can't figure out the problem . Thanks for advice.
success: function(data) {
//console.log(data); //dump
$.each(data, function(index, item) {
$('#load-more-div').append('<div class="blogItem"> ' +item.date, item.title.rendered+ 'Read More </div>' );
$("#loading-image").hide(); //remove gif
if ( data.item < 9 ) {// Remove the button if the response returns less than a full list of items
//loadMoreButton.remove();
document.getElementById("load-more").hide
}
}); //each
} //success
I think data.length is the number.
data.item.length is always going to return 1, as it’s inside the $.each() (OK, if it’s an array it may return something else)
So, your code should be
if ( data.length < 9 ) {
// your code here
} else {
// do something, like unhide the items
}
And you can take it out from the $.each() as you don’t need to check it for each item in data
Without fully understanding what data.item is, I added a .length to the end of it, which should give you length, in terms of an integer, that you are looking for.
success: function(data) {
//console.log(data); //dump
$.each(data, function(index, item) {
$('#load-more-div').append('<div class="blogItem"> ' +item.date, item.title.rendered+ 'Read More </div>' );
$("#loading-image").hide(); //remove gif
if ( data.length < 9 ) {// Remove the button if the response returns less than a full list of items
//loadMoreButton.remove();
document.getElementById("load-more").hide
}
}); //each
} //success
Here is my code:
$( "#targetButton" ).click(function() {
$.ajax({
url: './checkcolors.php',
type: 'post',
data: {
url: 'http://www.sportsdirect.com/dunlop-mens-canvas-low-top-trainers-246046?colcode=24604622',
SizeId: '6.5'
},
dataType: 'text',
success: function (data) {
var arr = data.split(',');
arr.forEach(function(id){
$('#' + id.trim()).show();
});
}
});
});
This is a ajax post function which is returning an number if ids.
The returned ids are answering to div html elements which i have to show.
These html div elements have same class but all of them are with different ids.
So i tried this code to select all elements with same class but excluding the elements with the pointed ids:
$('.ColorImagesNOColor:not(#' + id.trim() + ')').show();
It seems it is not working because it shows all elements with this class even with the ids which must NOT be shown.
Can you please help me out ?
Thanks in advance!
You're doing it inside a .forEach loop. That means that the last $('.ColorImagesNOColor:not(#' + id.trim() + ')').show(); will determine the final visibility of the .ColorImagesNOColor elements.
If you want to show all .ColorImagesNOColor elements and hide the ones with the id's returned, then you can move the first step to before the .forEach loop:
// Show all initially
$('.ColorImagesNOColor').show();
// Hide ones with certain Id's
arr.forEach(function(id){
$('#' + id.trim()).hide();
});
I update a certain content of htm element with setInterval function to call an ajax every few sec
<div class="content">
<p>New informaton here</p>
<br>
<p>.......</p>
more information below
</div>
below is the javascript
var main = function(){
updatingMessage = setInterval(function(){
$.ajax({
type: "POST",
url:" call_MYSQLDatabase_To_Update_Content.php",
cache:0,
data:({
some vars
}),
success:function(result){
$(".content").html(result);
}
});
}, 1000);
updatingMessage();
}
$(document).ready(main);
What's bother me is everytime when I scroll down to see the information
it will scroll to the top of itself after each ajax call. Is there anyway to stay at the same <p>'s position after an ajax call ?
First you must get the element's scroll position, then make sure you maintain that position by setting the scrollTop attribute to the original position.
var position = element.scrollTop;
//do some work here, which might change the position
element.scrollTop = position;
In my case, I have a table with overflow-y: auto and a fixed height: 350px. The .scrollTop() function does not work. Indeed, I tried to read the Y position of <table> or <tbody>, but it always returns 0!
When I refresh my <table>, the browser reset scroll position on my tables ! I absolutely need to prevent this.
Here is my workaround :
update only the contents of <tbody> instead of the entire <table>
It works fine, the scroll position of my tables is not reset.
Below is a part of my code that updates 3 tables every 10 seconds:
function updateTables() {
jQuery.ajax({
url: '/get-tables.php',
dataType: 'json',
type: 'get',
data: {
tableId: [
'table-actual',
'table-new',
'table-history'
]
},
success: function(response){
jQuery.each(response, function (key, table) {
jQuery('#table-' + table.id + ' tbody').html(data.content);
});
}
});
}
setInterval(updateTables, 10000);
Hope it helps some of you.
I'm using Freebase Search Suggest to bind a certain keyword to a getJson request. The problem is that I bind getJson functions and the corresponding .append/.prepend functions to to the input field that has the search suggest. Now if want to clear(.empty) my div that contains the result from the getJson functions i end up not being able to appennd anything.
So every time I do a search the result div stays empty. If I not try to run the empty function and do a second search, the new information gets appended on top of the previous information.
My site www.karsten-tietje.dk/sw
$('#myinput').suggest({key: "<mykey>","filter": "(all type:/music/musical_group )"
})
.bind("fb-select", function(e, data) {
$.getJSON("http://ws.spotify.com/search/1/track.json?q="+search_val, function(data) {
items = [];
$.each(data["tracks"], function(key, val) {
items.push('<li class="spot"><span typeof="MusicRecording" property="track"><p>Name: <strong><span property="name">' + val["name"] + '</span></span></strong></p> <p>Album <strong>' + val.album["name"] + '</strong></p><p> Released: <strong>' + val.album["released"] +'</strong></p><p><strong><i class="icon-play-sign"></i> Start Spotify</strong></p>');
if ( key === 7 )
{
return false;
}
});
$('#spotify-div').prepend('<h3 style="border-bottom:1px solid white;">Spotify tracks</h3>');
$('#spotify').html(items.join('</li>'));
});
});
This is just a snippet of my some of my code. I run multiple getJson functions.
How can I clear/empty my result div before running the other functions?
Lots of people have explained the mechanics of clearing, which it sounds like you already understand, so perhaps the missing piece is when to do it. You probably want to clear things as the very first thing in your Freebase Suggest select callback, before you fire off any of the queries to other services like Spotify (i.e. before the first $.getJSON()).
Not related to your question, but don't forget the attribution requirement of the Freebase license (not currently provided on your web site).
EDIT: Here's your code with empty added:
$('#myinput').suggest({key: "<mykey>","filter": "(all type:/music/musical_group )"
})
.bind("fb-select", function(e, data) {
$('#spotify-div').empty(); // empty the div before fetching and adding new data
$.getJSON("http://ws.spotify.com/search/1/track.json?q="+search_val, function(data) {
items = [];
$.each(data["tracks"], function(key, val) {
items.push('<li class="spot"><span typeof="MusicRecording" property="track"><p>Name: <strong><span property="name">' + val["name"] + '</span></span></strong></p> <p>Album <strong>' + val.album["name"] + '</strong></p><p> Released: <strong>' + val.album["released"] +'</strong></p><p><strong><i class="icon-play-sign"></i> Start Spotify</strong></p>');
if ( key === 7 )
{
return false;
}
});
$('#spotify-div').prepend('<h3 style="border-bottom:1px solid white;">Spotify tracks</h3>');
$('#spotify').html(items.join('</li>'));
});
});
Select the element and put HTML blank like below
jQuery('#selector').html('');
then after apply the append jquery function on same selector like below
jQuery('#selector').append("<p>text</p>");
You can also do this by clearing the inner html of the html, with id "spotify":
$('#spotify').empty();
With jQuery there can be many ways of emptying an element of its contents and appending/prepending content.
One is .empty(); ( Documentation )
$('#spotify-div').empty().prepend('<h3>YourHTML Here</h3>');
Another is .html( [ html ] ); ( Documentation )
$('#spotify-div').html('').prepend('<h3>YourHTML Here</h3>');
If you are changing the html and not worried about keeping events, you could just pass your html through the .html( 'Your HTML' ); function
$('#spotify-div').html('<h3>YourHTML Here</h3>');
I have picked up this AJAX code from multiple tutorials, but the problem is, when the ajax is called, the div ALWAYS scrolls to the bottom. But I want it so that the div ONLY scrolls if there are new messages in the div.
$.ajax({
url: "msg-handle/get-messages.php",
cache: false,
data: { room: $("#room").val() },
success: function(data) { $('#chat').html(data)
$("#chat").scrollTop($("#chat")[0].scrollHeight);
},
});
}, 500);
Is there a way to achieve this without any major ramifications to my code?
I didn't try it, but I think it has to be something like this... (among other solutions)
var oldscrollHeight = $("#chat")[0].scrollHeight;
//Takes the height BEFORE reload the div
$.ajax({
url: "msg-handle/get-messages.php",
cache: false,
data: { room: $("#room").val() },
success: function(data) { $('#chat').html(data)
var newscrollHeight = $("#chat")[0].scrollHeight;
//Takes the height AFTER reload the div
if(newscrollHeight > oldscrollHeight){ //COMPARES
$("#chat").scrollTop($("#chat")[0].scrollHeight); //Scrolls
}
},
});
I think You have to put a $("#chat").scrollTop($("#chat")[0].scrollHeight); after the first load of the chat.. just an advise.
the easiest way would be to let the php script pass a flag when there are new messages in the div. you then just have to put in a check condition for the the scrolling.
another option would be to compare the number of divs in the new .get() result to the previous one and scroll only if there are more divs present in the current.