Wasn't quite sure how to ask this, but anyways.
I am automatically adding divs (in php) depending on the id's stored in an array, and I'd like to refresh every existing div with a different value. Here's an example of what the divs look like:
<div class="panel-heading" >
<h4 class="panel-title" id="reload$device_id">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse$device_id">Data: $device_data</a>
</h4>
</div>
I'm trying to reload the elements with the id "reload$device_id" (currently have 2 different id's, so it'd be reload1 and reload2).
Thank you for your help!
p.s: first time posting a question, not sure how this will work
Edit1: had a <=device_id_list.length instead, quick typo was fixed.
Edit2: Current code, pretty similar, only reloads first one :/
<script type="text/javascript">
var device_id_list = <?php echo json_encode($device_id_list);?>;
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
for (var i = 1; i < device_id_list.length + 1; i++) {
$("#reload" + i).load("reload_data.php?device=" + i);
}
}, 5000);
});
</script>
Its seems you echo out json_encode($device_id_list) and use php in javascript just to use device_id_list.length in for loop !! if I'm right .. you can use
<script type="text/javascript">
$(document).ready(function(){
setInterval(function() {
$('[div^="reload"]').each(function(){
$(this).load('reload_data.php');
});
}, 5000);
});
</script>
hope it help
Turns out my problem wasn't on the javascript portion of my script, but rather when I was filling up the $device_id_list array. I wasn't doing it correctly, hence why it wasn't reloading all of the divs.
Here's my javascript anyways:
<script type="text/javascript">
var device_id_list = <?php echo json_encode($device_id_list);?>;
$(document).ready(function() {
$.ajaxSetup({ cache: false }); // This part addresses an IE bug. without it, IE will only load the first number and will never refresh
setInterval(function() {
for (var i = 0; i < device_id_list.length; i++) {
var device_id = device_id_list[i];
$("#reload" + (device_id)).load("reload_data.php?device=" + (device_id));
}
}, 5000);
});
</script>
Related
Got a webpage which is used for voting on different pictures (voting-tool).
On the page there are 2 different ad-banners which are stored in div containers.
The ads themselves get loaded by a script which fills the divs with the ads. (just as regular).
Now my problem is that the ads should reload after 5 pictures are clicked or after an amount of time. The option of page reload is also not possible. If the page is refreshed the pictures start at picture 1 again, so its not very useful if the viewer already is at like picture 10.
How can we reload a script / a single div container on a page so that the page stays exactly the same and only the ads reload and show another banner?
Any help is really appreciated.
Note:
I've already tried it with
document.getElementById("addBoxOne").innerHTML
It works fine for text or pictures but not for a script and with
document.write("")
While using the document.write the whole page gets overwritten and not only the div itself. and I cant figure out how to only rewrite / refresh the Adbox
edit: script of the ad-banner
<div class="superbanner">
This is the div where the ad-banner is in and which i want to reload
<script language="JavaScript">
if (typeof (WLRCMD) == "undefined") {
var WLRCMD = "";
}
if (typeof (adlink_randomnumber) == "undefined") {
var adlink_randomnumber = Math.floor(Math.random() * 10000000000)
}
document
.write('<scr'
+ 'ipt language="JavaScript" src="http://ad.de.doubleclick.net/adj/oms.skol.de/localnews_bilder;oms=localnews_bilder;reg=;nielsen=3b;dcopt=ist'
+ WLRCMD + ';sz=728x90;tile=1;ord='
+ adlink_randomnumber + '?"><\/scr'+'ipt>');
</script>
<noscript>
<a
href="http://ad.de.doubleclick.net/jump/oms.skol.de/localnews_bilder;oms=localnews_bilder;nielsen=3b;sz=728x90;tile=1;ord=1734775579?"
target="_blank"><img
src="http://ad.de.doubleclick.net/ad/oms.skol.de/localnews_bilder;oms=localnews_bilder;nielsen=3b;sz=728x90;tile=1;ord=1734775579?"
border="0" width="728" height="90"></a>
</noscript>
<div class="clear"></div>
Try using AJAX instead of Document.write. . doc.write will remove everything in the dom before adding new stuff..
$.ajax({
url: "http://ad.de.doubleclick.net/adj/oms.skol.de/localnews_bilder;oms=localnews_bilder;reg=;nielsen=3b;dcopt=ist",
dataType: "script",
cache: true,//This will decide whether to cache it or no so that it will not add the timestamp along with the request
success: function(){}//In the success handler you can write your code which uses resources from this js file ensuring the script has loaded successfully before using it
});
<body class="white">
<h1 class="black">3 seconds image.</h1>
</body>
.white {
background-color:#FFFFFF;
color:#000000;
}
.black {
background-color:#000000;
color:#FFFFFF;
}
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function changeColor(){
if ($('body').hasClass('white')) {
$('body').removeClass('white');
$('body').addClass('black');
$('h1').removeClass('black');
$('h1').addClass('white');
}
else {
$('body').removeClass('black');
$('body').addClass('white');
$('h1').removeClass('white');
$('h1').addClass('black');
}
}
setInterval(changeColor, 3000);
});
</script>
other. see here documentation
$(document).ready(function() {
// Put all your code here
setInterval(function() {
//$("#content").load(location.href+" #content>*","");
$("#content").load('image.png').fadeIn("slow")
}, 5000);
});
// simple example using the concept of setInterval
$(document).ready(function(){
var g = $('.jumping');
function blink(){
g.animate({ 'left':'50px'
}).animate({
'left':'20px'
},1000)
}
setInterval(blink,1500);
});
I've been struggling with this all day.. I've got a couple of posts, each have a next and previous button. The idea is for each post and its next and previous buttons, to scroll the window to the next post or previous post. I have tried using the each() function and unfortunately, its tricky to get working.
This is the jQuery so far:
var scrollTo = function(element) {
$('html, body').animate({
scrollTop: element.offset().top
}, 100);
}
function prev_next_scrolling() {
var articles = $("article.post"),
counter = 0;
articles.each( function() {
var articles = $(this);
$('.next-btn', articles).click( function() {
scrollTo($('article.post').eq(counter + 1));
});
$('.prev-btn', articles).click( function() {
scrollTo($('article.post').eq(counter - 1));
});
counter++;
});
}
prev_next_scrolling();
And this is the HTML:
<article class="post">
<h2>Post Title</h2>
<p>Post description</p>
Previous
Next
</article>
Here is the jsfiddle link for you guys to have a looksie!
http://jsfiddle.net/casacoda/2zM3Q/
Any help will be much appreciated! Thanks in advance guys!
The problem with your code is that counter is defined in the scope of prev_next_scrolling(), so all the functions run by the each() method will use the very same instance of the variable. Each time you increase counter, that will happen for all places where it has been used.
You can fix that by introducing a variable local to the function that handles a specific element -- or actually, you don't have to because jQuery already gives you exacly that as an optional parameter in the each() callable. See http://api.jquery.com/each/
So here's the correct code (http://jsfiddle.net/2zM3Q/3/):
var scrollTo = function(element) {
$('html, body').animate({
scrollTop: element.offset().top
}, 100);
}
function prev_next_scrolling() {
var articles = $("article.post"),
counter = 0;
articles.each( function(index) {
var articles = $(this);
$('.next-btn', articles).click( function() {
scrollTo($('article.post').eq(index + 1));
});
$('.prev-btn', articles).click( function() {
scrollTo($('article.post').eq(index - 1));
});
counter++;
});
}
prev_next_scrolling();
There are still some problems: It doesn't check whether it already is the first/last post and if it's already at the end of the page it obviously won't scroll any further, creating the illusion of a "broken" link (because nothing seems to be happening after clicking it.)
I've updated the fiddle to address all your concerns in the comments
Updated Working Fiddle
I got it working without all your each code, just navigating the dom.
Let me know if you have questions about the Fiddle provided. Basically this takes advantage of your current structure being known, it finds the next ARTICLE using parent().next() and then finds that ARTICLEs h2. It then uses the H2s vertical offset position to scroll to it. Same for previous links but using parent().prev()
$(document).on('click', '.next-btn', function(){
// find the next anchor
var nextAnchor = $(this).closest('article').next().find('h2')
$('html,body').animate({scrollTop: nextAnchor.offset().top},'slow');
});
$(document).on('click', '.prev-btn', function(){
// find the previous anchor
var prevAnchor = $(this).closest('article').prev().find('h2')
$('html,body').animate({scrollTop: prevAnchor.offset().top},'slow');
});
One thing to note, if the H2 in question is already visible on the screen it will not scroll UP to anything, only if its off screen will it scroll UP to it. Scroll down will always move the screen if needed.
I am developing a application with phonegap. on my pc everything runs fine but on my mobile device its just too slow.
i think the problem is on the show function, the android browser seems to needs really long to hide and show elements
what can be improved?
function show(id){
$('.view').hide()
//alert('show ' + id)
$('#'+id+'View').show()
scroll(0,0)
}
function getSoundHTML(id, myname, del){
if (del != true){
var imgsrc = 'plus.png'
var f = function(){
addToCostumSounds(id)
alert('added to favorites')
}
}else{
var imgsrc = 'minus.png'
var f = function(){
removeFromCostumSounds(id);
$(this).fadeOut().next('div').fadeOut();
}
}
var div = $('<div></div>').addClass('box').html(myname).css('border-color', '999999').click(function(){
play(id)
})
var img = $('<img></img>').attr('src', imgsrc).addClass('sideimg').click(f)
return $('<div></div>').append(img).append(div)
}
for(var category in categories){
var f = function(category){
$('#'+category+'Btn').click(function(){
show(category)
var categoryView = $('#'+category+'View')
for(var key in categories[category]){
var div = getSoundHTML(key, categories[category][key])
categoryView.prepend(div)
}
var img = '<img src="menu.png" class="menuimg"/>'
categoryView.prepend(img)
categoryView.append(img)
})
}
f(category)
}
the html:
<div class="btn" id="noBtn">no _</div>
<div class="btn" id="thatIsBtn">that is _</div>
<div class="btn" id="thereIsBtn">there is _</div>
<div class="btn" id="thisIsBtn">this is _</div>
...
<div class="view" id="noView"></div>
<div class="view" id="thatIsView"></div>
<div class="view" id="thereIsView"></div>
<div class="view" id="thisIsView"></div>
...
Whilst it may not have an effect on Desktops, your massive lack of semi-colons in the right places may have an effect on mobile devices.
The JavaScript engine has to run through and try to work out where the semi-colons need to go. See this transcript from the ECMAScript specification.
To be honest I think thats only a few milliseconds of time-saved, but its a starting point for now - and good practice for the future.
Here's your problem:
for(var category in categories){
var f = function(category){
...
for(var key in categories[category])
...
}
f(category)
}
You have two BIG issues here:
You're defining a function within a loop. While this is sometimes needed, you should do your very best to avoid defining things within a loop unless you absolutely need to. In this case, you could probably move the f function out of the loop entirely without breaking your code.
Nested loops. You have a for ... in within a for ... in loop. This is largely due to the first problem I pointed out, but in general nested loops are a big no-no from a performance standpoint.
ok, i think i got the only way to improve the peroformance:
if someone clicks on a button (class="btn") he is redirected to a new fresh page that has the entire page in HTML and does not build it with javascript.
I am trying to learn some of the more advanced java scripting patterns while using jQuery to ease some of the ajax difficulty with jQuery. However, I keep running in to problem that throws no errors.
I want to be able to call the ajaxCalls.setup({}) and have it replace the defaults with the object passed to setup. I have that part working. What I seem to have problems with is the ajax call. When the callIt function runs the $(this.defaults.element).load(....) does not run or if it does it fails. I am pretty stumped. I am really just trying to learn something new. I would appreciate any help
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
var ajaxCalls = (function($){
var ajaxer = {
defaults:{
url:"test.php",
element:"#ajaxerizer"
},
setup:function(setup){
var defaulLengther = this.defaults
/*var l = 0;*//*bug*/
for (var key in defaulLengther)
{
if(setup.hasOwnProperty(key))
{
this.defaults[key] = setup[key];
/*l++;*//*bug*/
}
}
/*debugger*/
/*for(var i=0; i < l; i++)
{
alert(this.defaults.power);
} */
this.callIt();
},
callIt:function(){
$(this.defaults.element).load(this.defaults.url, function(){alert("success");});
},
}
return ajaxer
})(jQuery);
ajaxCalls.setup({})
</script>
</head>
<body>
<div id="ajaxerizer"></div>
</body>
</html>
Thank you for your help test.php just has this in it
<p>IT WORKED</p>
a note: in this project I intended to only use jQuery for DOM selection and aJax calls
You need to set your ajaxCalls.setup to run after the page is loaded using document.ready
eg.
$(document).ready(function(){
ajaxCalls.setup({})
});
Otherwise you're trying to replace your div before the html is loaded.
I am aware that when coding an extension, there is no way we can delay a function call except for using a setTimeout call but here's what I am trying to achieve in a plugin that I am developing for Firefox (this is not for Javascript embedded into a web page by the way):
for (var i = 0; i < t.length ; i++) {
//Load a URL from an array
//On document complete, get some data
}
The idea is simple. I have an array of URLs that I want to parse and extract some data out of. Each of these URLs take some time to load. So, if I try to get some data from the current page without waiting for the page to load, I will get an error. Now, the only way to do this as I know is as follows:
firstfunction: function() {
//Load the first url
setTimeout("secondfunction", 5000);
}
secondfunction: function() {
//Load the second url
setTimeout("thirdfunction", 5000);
}
And so on... I know this is obviously wrong.. I was just wondering how people achieve this in Javascript...
EDIT: Sorry about not being more detailed...
I'm not convinced that this type of foolery is necessary but I'm not an extension dev so who knows. If this is the approach you want, then just have the setTimeout call refer to the same function:
var index;
firstfunction: function() {
// do something with `index` and increment it when you're done
// check again in a few seconds (`index` is persisted between calls to this)
setTimeout("firstfunction", 5000);
}
I am not sure how to do this from a plugin, but what I've done with iframes in the past is attach a callback to the target document's onLoad event.
Maybe something like:
var index = 0;
var urls = [ ..... ];
function ProcessDocument() { ....; LoadNextDocument(); }
function LoadNextDocument() { index++; /* Load urls[index] */; }
document.body.onLoad = ProcessDocument;
Somewhere in there you'd need to test for index > urls.length too for your end condition.
I had same problem but I used recursion instead of looping.
Below is the running code which changes the innerHTML of an element by looping through the list. Hope its helpful.
<Script type="text/javascript">
var l;
var a;
function call2()
{
l = document.getElementById('listhere').innerHTML;
a = l.split(",");
call1(0);
}
function call1(counter)
{
if(a.length > counter)
{
document.getElementById('here').innerHTML = a[counter];
counter++;
setTimeout("call1("+counter+")",2000);
}
}
</Script>
<body onload="call2()">
<span id="listhere">3,5,2,8</span><Br />
<span id="here">here</span>