jQuery animation if load() returns something different - javascript

setInterval(function() {
var prevTopArticle = $("#toparticles table:first").html();
$("#toparticles").load("myurloffeed.com/topfeed", function()
{
alternateBG();
var newTopArticle = $("#toparticles table:first").html();
if (prevTopArticle!=newTopArticle)
{
$("#toparticles table:first").effect("highlight", {color:"#faffc4"}, 2000);
}
});
}, 8000);
So it sets the current first table item to a variable, loads the toparticles div with the tables off the url, and if they are different it will perform the highlight effect, however it does the highlight effect anyway, completely unsure why it isn't working.

For some reason one of the articles was outputting a twitter link and the other wasn't, thought the feeds were the same. Figured it out using console.log of the two variables.

Related

Use jQuery to determine when Django's filter_horizontal changes and then get the new data

I have a filter_horizontal selector in my Django admin that has a list of categories for products (this is on a product page in the admin). I want to change how the product change form looks based on the category or categories that are chosen in the filter_horizontal box.
I want to call a function every time a category is moved from the from or to section of the filter_horizontal.
What I have now is:
(function($){
$(document).ready(function(){
function toggleAttributeSection(choices) {
$.getJSON('/ajax/category-type/', { id: choices}, function (data, jqXHR) {
// check the data and make changes according to the choices
});
}
// The id in the assignment below is correct, but maybe I need to add option[]??
var $category = $('#id_category_to');
$category.change(function(){
toggleAttributeSection($(this).val());
});
});
})(django.jQuery);
The function never gets called when I move categories from the left side to the right side, or vice versa, of the filter_horizontal.
I assume that $category.change() is not correct, but I don't know what other events might be triggered when the filter_horizontal is changed. Also, I know there are multiple options inside of the select box. I haven't gotten that far yet, but how do I ensure all of them are passed to the function?
If anyone can point me in the right direction I would be very grateful. Thank!
You need to extend the SelectBox.redisplay function in a scope like so:
(function() {
var oldRedisplay = SelectBox.redisplay;
SelectBox.redisplay = function(id) {
oldRedisplay.call(this, id);
// do something
};
})();
Make sure to apply this after SelectBox has been initialized on the page and every time a select box refreshes (option moves, filter is added, etc.) your new function will be called.
(Code courtesy of Cork on #jquery)
I finally figured this out. Here is how it is done if anyone stumbles on this question. You need to listen for change events on both the _from and _to fields in the Django filter_horizontal and use a timeout to allow the Django javascript to finish running before you pull the contents of the _from or _to fields. Here is the code that worked for me:
var $category = $('#id_category_to');
$category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
var $avail_category = $('#id_category_from');
$avail_category.change(function(){
setTimeout(function () { toggleAttributeSection(getFilterCategoryIds()) }, 500);
});
And this is how I get the contents of the _to field:
function getFilterCategoryIds() {
var x = document.getElementById("id_category_to");
var counti;
var ids = [];
for (counti = 0; counti < x.length; counti++) {
ids.push(x.options[counti].value);
}
return ids;
}
I know it was a convoluted question and answer and people won't come across this often but hopefully it helps someone out.

Appending new results to an open jQuery autocomplete menu

I have an app in which I have multiple search sources. Previously, the users had to choose in what source to search in before searching. If they did not choose, the app would default to one of the options.
However, now they want to search in all the sources at the same time. This is fine enough, but the problem is that when one of the searches returns, it overwrites the previous search result. Pretty much expected behavior. What I basically want is to append the new results to the already open autocomplete menu, instead of overwriting the old results. Naturally, the autocomplete menu would have to empty when it closes.
I guess that this is possible to do, but what approach is the best? I could just have an array I guess, which I append results to and then overwrite _renderMenu to use this array instead of the items one that is passed to the function. Then empty said array at the close event.
Is this the best way to go though? Or is there a more elegant solution?
Some code:
Ok, so searchAction is called by jquery autocomplete eventually. In collection.search I do the ajax call, here the URL is created based in the this parameter, then respondWhithData is called and maps the search result to a proper format (ie value and label for the autocomplete menu). After reponse is called from respondWithData, jquery automagically renders the resultsmenu. Thus, I probably have to overwrite the reponse event function as well as the _renderMenu and possibly _renderItem, yes?
searchAction: function(searchTerm, collection, response){
var self = this;
$.when(collection.search(searchTerm, this)).then(function(data) {
self.respondWithData(data, response);
});
},
respondWithData : function(data, response) {
if (data.length > 0) {
var responseVal = _.map(data, this.mapData);
this.checkResponseCount(responseVal);
response(responseVal);
}
else {
response(this.emptyResult());
}
},
To be clear, the problem is not the multiple search itself, but rendering the asynchronos results. I want to render the first results that come back, and then appends the rest as soon as they are returned from the server.
Edit 2:
Just tried to edit ui.content in the autocompleteresponse event, but any edit does not take once it renders for some reason...
Edit 3: Ah, ui.content can only be modified directly, not changed. If I push every single change instead of concating two arrays ui.content shows what I want.
It works I guess, but its not perfect.
I can figure how looks your scenario but I'm guessing:
You should have like:
function search1() {
$.ajax({ ...
success: function(data) {
$('#myResultsDiv").html(data)
}
});
}
etc
Instead of overwritting the #myResultsDiv you need to Append the results like:
function search1() {
$.ajax({ ...
success: function(data) {
$('#myResultsDiv").append(data)
}
});
}
Edit: You can also do something like this:
var resultsArray = [];
var searchDone = 0;
var totalSearchs = 5; //assuming 5 searches
function search1() {
function search1() {
$.ajax({ ...
success: function(data) {
//APPEND data to resultsArray
searchDone++;
if(searchDone==totalSearch) //syncronize the 5 searchs before render
renderSearchs(resultsArray);
}
});
}

Click on table causes multiple ajax operations are running with jQuery

after looking for a solution of a problem I may found the turning point and can define the problem.
My code uses jQuery and Ajax and is triggered on a click on a table cell. The output was and is a table which I refresh within an interval.
Well, when I clicked on a cell and then on another cell the output is switching between the outputs based on the transmitted value of cell A and cell B.
I took a look into firebug and, voila, got a sneak on the reason.
GET http://localhost/trading/getuser_exp.php?q=NYSE
GET http://localhost/trading/getuser_exp.php?q=NASDAQ
Both values are running parallel and this is wrong. I need a single value or, in other words, if I clicked on NYSE before, value is NYSE, then I click on NASDAQ, the value isn't NYSE anymore, but NASDAQ.
The code is use is
$(document).ready(function(){
$(".information").click(function () {
var str = $(this).closest("tr").find("#nr").text();
window.setInterval(function(){
$.get("getuser_exp.php",
{ q:str },
function(data) { $('.stock').html(data);
} //function data
);
}, 3000);
}); //information click
}); //document ready
Now what causes the multiple firing? In my eyes - frank speaking a beginner - nothing is multiple firing or that is accepting multiple values. Whatever it is, I will learn.
Thank you for any assistance and help.
You need to clear the old interval and start a new one. This is why you get multiple firings as each click starts a new interval timer.
$(document).ready(function(){
var timer = null;
$(".information").click(function () {
var str = $(this).closest("tr").find("#nr").text();
if(timer!=null) {
clearInterval(timer);
}
timer = window.setInterval(function(){
$.get("getuser_exp.php",
{ q:str },
function(data) {
$('.stock').html(data);
}
);
}, 3000);
});
});

Javascript Refresh

Is there a way using the code below to instead of refreshing the time refresh a div id that is already there?
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('drawaddrow').innerHTML = ????;
}
</script>
Say I fi were to replace the time id with the the id that I wanted to refresh what would I put after .innerHTML =???
This is the div I need refreshed every second.
<div id="draw" align="center">
<table>
<tr><td style="height:20px;"></td></tr>
</table>
<TABLE style="float:center;border:5px; border-style:outset;border-color:#E80000; width:850px; border-spacing:0; border-collapes:collapse;" table border="1">
<div id="addrow"><script type="text/javascript">
Draw ("")
[Add]</script></div>
</table>
</div>
The [AddItemsHTML] somehow pulls data from a piece of software telling you what is due and what is not, however the script is not pulling the time every second the browser when refreshed just changed the time on the due status column.
Right now i'm using this to refresh the whole page I just need the drawaddrow div id refreshed.
function refreshPage () {
var page_y = document.getElementsByTagName("body")[0].scrollTop;
window.location.href = window.location.href.split('?')[0] + '?page_y=' + page_y;
}
window.onload = function () {
setTimeout(refreshPage, 1000);
if (window.location.href.indexOf('page_y') != -1 ) {
var match = window.location.href.split('?')[1].split("&")[0].split("=");
document.getElementsByTagName("body")[0].scrollTop = match[1];
}
Updated (on 27/07/2013 #08:20 AM IST):
Having gone through your code, the below is my updated answer.
Plainly assigning a value to the DIV (divaddrow) using (.innerHTML) wouldn't work due to the following reasons:
(a) The DIV has some code enclosed within square braces (like [AddItemsHTML]). I am not sure what technology it uses. But judging by its intended use (which is, to populate the table with data) it sure seems to require a communication with the server to fetch data.
(b) The DIV also has a <script> tag with a call to a function (lets call it cntFn). Plainly assigning the value would not work because value setting wouldn't call/execute the function again (like it does on page load).
Assuming point 1.a is wrong, the normal way to handle 1.b would be to first assign the static contents of the div using .innerHTML and then do either (a) write whatever the "cntFn" does into the function that is refreshing the page (lets call it refreshFn) also (or) (b) call the "cntFn" within the "refreshFn". The latter would also cause a problem here because the "cntFn" has a lot of document.write lines which would repaint the entire page (meaning the other contents of the page would be lost on executing the refresh).
Generally using document.write lines is a bad practice because they repaint the page fully. You can find more about this here.
The best alternate in my opinion would be to use AJAX to refresh the contents. The content of your divaddrow div would form the contents of the AJAX file that needs to be called every 'x' seconds. Be careful with the 'x' seconds part. Do not try to refresh the section every second because realistically it would take time for the AJAX request to reach the server and get the response. Set the refresh interval such that the first request would have been processed by the time the next one comes (at-least 90% of the cases). The amount of data (no. of rows) that the AJAX call would be fetching will also be a factor.
Check this out... I used Jquery for the same
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor(Math.random() * 100);
$('#show').text(
'I am getting refreshed every 3 seconds..! Random Number ==> '
+ randomnumber);
}, 3000);
});
WORKING FIDDLE
I'm not sure that I understand you, but is this want you mean?
function startTime()
{
document.getElementById('time').innerHTML = document.getElementById('target').innerHTML;
}
This is what I use:
<span>This page will refresh in </span><span id="countdown">60</span>seconds…
<script type="text/javascript">
setInterval(
function() {
if (document.getElementById('countdown').innerHTML != 0) {
document.getElementById('countdown').innerHTML--;
} else {
window.location = window.location;
}
}, 1000);</script>
If I've understood your question correctly, you can do something like this:
window.onload = function () {
function startTime () {
document.getElementById('date').innerHTML = new Date();
}
setInterval(startTime, 1000);
}
HTML:
<div id="time">This a div containing time: <span id="date"></span></div>
This is a JavaScript snippet, based on the original post, that counts the number of seconds since the page has loaded, assuming that there's an element with ID "time" and contents that are entirely numeric.
If the time remaining is given in seconds on the page you're working with, then it would be easy to adjust this accordingly. If the time remaining is not given in seconds, I'd need to see what the text in question actually looks like.
window.onload = startInterval;
var firstTime;
var valAtPageLoad;
function startInterval()
{
firstTime = new Date();
valAtPageLoad = parseInt(document.getElementById('time').innerHTML);
setInterval("startTime();",1000);
}
function startTime()
{
var timeDiff = (new Date() - firstTime)/1000;
document.getElementById('time').innerHTML = Math.round(timeDiff + valAtPageLoad);
}
If you want to reload your DIV and not the entire page, you would have to create the contents of that DIV on the server-side, and then use AJAX to load the DIV´s content. The easiest way to do this, is with jQuery:
function startTime() {
$.get('path/to/div/contents.html', function(data) {
$('#drawaddrow').html(data);
});
}

Autorefresh div with javascript

I have been looking around for the simplest way to refresh a particular div on my page, automatically, every x seconds.
So far I've got:
<script type="text/javascript">
window.onload = startInterval;
function startInterval()
{
setInterval("startTime();",1000);
}
function startTime()
{
document.getElementById('time').innerHTML = Date();
}
However the last part where the innerHTML is set to the date function is what I'd like replaced by the content of the "time" ID, and not an actual date print.
I know I could load an iframe, or externa html page, but I would like to simply call upon an existing div on the page instead of having to change the existing content. Is that possible?
Thanks!
Edit: What I mean is I have a a div that looks like this on the page:
Some stuff
I would like to have that div refreshed every x seconds, so yes, you may ignore the Date() part of my example, I simply found that code as is but when I tried to remove the .innerHTML part it just does nothing, I think lol!
Are you looking for something like this?
<script type="text/javascript">
window.onload = startInterval;
function startInterval() {
setInterval("startTime();",1000);
}
function startTime() {
var now = new Date();
document.getElementById('time').innerHTML = now.getHours() + ":" + now.getMinutes() + ":" +now.getSeconds();
}
</script>
NOTE: The OP is actually wanting to reload a script in an ad service already included on the page. The following does not help with this; however, due to the way the question was asked, I'm leaving this answer since I think it could help others looking for the following type of solution. Just be aware this does not demonstrate how to "rerun" already included (presumably global and non-function'd) code.
Say I have the following div I'd like to dynamically refresh:
<div id="refresh">Refreshes...</div>
jQuery offers the $.ajax group of functions that allow you to dynamically request a page and use the response as HTML. For instance:
$(document).ready(function(){
var $refresh = $('#refresh'),
loaded = 1,
data = {
html: $.toJSON({
text: 'some text',
object: {}
}),
delay: 3
};
var refresh = function(){
$.ajax({
url: "/echo/html/",
data: data,
type: "GET",
success: function(response) {
$refresh.html($refresh.html() + '<br/>#' + loaded);
loaded++;
setTimeout(refresh, 3000);
}
});
};
refresh();
});
http://jsfiddle.net/Ah3jS/
Note, I'm using jsFiddle's echo/html/ functionality here as well. The data variable is tuned to working with this for demonstration purposes. In reality, the data sent with the request is either GET or POST variables like you work with normally. Also, I don't use response in success, but that's because it doesn't return anything in jsFiddle's demo mode.
jQuery make's this stuff pretty easy. Really, I'd think about using it instead of most other approaches (requirements notwithstanding).

Categories