Refreshing an ad-banner in a div container - javascript

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);
});

Related

Get an element in an <embed> tag

I'm a beginner in Javascript and i'm trying to get an element from an embed tag. This embed tag contains a pdf.
I want to get the button "next page" from the pdf viewer, and simulate a click on it, in order to automaticly scroll to the next page of the pdf.
My HTML code is something like this (really simplified) :
<html>
<body>
<div id="display-zone">
<embed id="myPdf" src="./myPdf.pdf">
#document
<html>
<body>
<!-- The button I want to get in my JavaScript -->
<button id="next" class="toolbarButton pageDown"></button>
</body>
</html>
</embed>
</div>
</body>
</html>
My JS code to print the pdf viewer on the web page :
affichage.innerHTML = "<embed class=\"media\" id=\""+ongletsMedias[i].firstChild.data+"\" src= \""+ongletsMedias[i].firstChild.data+"\" width= \"1000\" height= \"800\">";
// ongletsMedias[i].firstChild.data equals to "myPdf"
t = 5000; // time before starting pdfDefile()
setTimeout(pdfDefile,t,ongletsMedias[i].firstChild.data,i,1); //call the function to scroll pdf pages
And finally my function pdfDefile() that I'm calling in order to scroll the pdf pages :
function pdfDefile(dir,i,page) {
var xhttp = new XMLHttpRequest();
var t = 0;
xhttp.onreadystatechange = function() {
var checkbox = document.getElementById('checkbox');
if (this.readyState == 4 && this.status == 200 && checkbox.checked) {
document.getElementById("span").innerHTML = this.responseText; // display the number of pages of my pdf
var t = 5000;
if (page < parseInt(this.responseText)) { //test for recursive call
/*HERE is where I want to get the "next" button */
setTimeout(pdfDefile,t,dir,i,page+1);// recall this function while there is a next page to display
} else {
setTimeout(jouerMedia,t,i+1);// call the main fuction, no problem here
}
}
};
xhttp.open("GET", "nbPagesPDF.php?pages="+dir, true);
xhttp.send();
}
I already look at an existing topic (Get element in embed tag), but I can't make it work in my JS.
So please, can you help me to make my code great again (may it have been ;-) ) ?
Regards
Try
var embed = document.getElementById('myPdf');
// Wait for document to load inside embed element
embed.on('load', function() {
embed.getElementById('next').click();
});
(I am using jQuery in this example for adding the event listener, not sure if you are using it on your project?)
Without jQuery you could do:
var embed = document.getElementById('myPdf');
embed.onload = function() {
embed.getElementById('next').click();
};
It might be possible you can not trigger a click event on that button since a user action often must have taken place to trigger click's from js.

jQuery - .load() each incremental id (ex: content1, content2, etc.)

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>

JavaScript/Jquery not executing my functions

I am trying to create a basic image rotate. I have my images stored locally by name in a folder called comics. each comic name is comic_(plus the number). It wont do anything when I click my buttons. It wont even disable my previous button. Please help. Thank you guys.
Here is my JS/Jquery...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//declare my variables
var comic_img = $('#comicpane').find('img')
var current_comic_number = parseInt(comic_img.attr('class').replace('comic_',''))
var prev_comic = current_comic_number - 1;
var next_comic = current_comic_number + 1;
});
if (current_comic_number == 1){
//disable the prev button
$("#prev").attr('disabled','disabled');
//When the user clicks on a nav item
$(".nav_link").on('click')function(){
//Get the button they clicked
current_button = $(This);
if (current_button.attr('id')) == 'next'
{
comic_img.attr('class','comic_') + next_comic + ".jpg";
comic_img.attr('src','comics/comic_1') + next_comic;
//change variables to reflect current comic
current_comic_number +=1;
next_comic +=1;
prev_comic +=1;
}
//Only other option
else
{
comic_img.attr('src','comics/comic_1') + prev_comic + '.jpg';
comic_img.attr('class','comic_') + prev_comic;
//Change variables to reflect comic
current_comic_number -=1;
next_comic -=1;
prev_comic -=1;
}
//If comic number is less or equal to 1 and prev button is Not disabled, it needs to be disabled.
if (current_comic_number <=1 && !$('#pev').attr('disabled','disabled'))
{
$('#prev').removeAttr('disabled')
}
}
}
</script>
Here is my HTML...
<html>
<head>
<title>SRS Comic Zone</title>
<link rel="stylesheet" href="srscomiczone.css" media="screen">
</head>
<body>
<div id="header">
<img id="header" src="HeaderPicture.png" align=center>
</div>
<div class="comiczone" id="comicpane" align=center>
<img class="comic_1" src="comics/comic_1.jpg">
</div>
<div id="comicNav" align=center>
<button id="prev" class="nav_link">Previous</button>
<button id="next" class="nav_link" >Next</button>
</div>
</body>
</html>
few mistakes,
1) this is how you call a click event
$(".nav_link").on('click',function(){
....
and not
$(".nav_link").on('click')function(){ //replace this with above code
you might also need to delegate your selector if it is added dynamically.....
2)
current_button = $(This);
should be
current_button = $(this);
3) also, notice..if you are using jquery 1.6+, use prop() instead of attr()
$("#prev").prop('disabled',true);
instead of
$("#prev").attr('disabled','disabled');
4) add all your codes inside document.ready $(document).ready(function(){ //here }); function and not outside.
5) most important, you either have to include the script (js file) inside you html page. or paste all your script codes inside <head> tag of your HTML file
Also this stuff should be wrapped by:
$(document).ready(function() {
$(".nav_link").on('click',function(){
...
});
not just your var declarations.
Your code is trashy. Better use tool like JS Hint (or other JS validator, or even Chrome/Firefox with web console) to actually make sure code can even run.
Here are (some) of the issues with it:
you're missing semicolons
your .ready() function is (as I believe) ending prematurely
you're doing click handling wrong (pointed out by #bipen)
your if statements are messed up
you (probably) haven't included scripts into the HTML document
Ad 1
Missing semicolon here:
var comic_img = $('#comicpane').find('img')
Ad 2
current_comic_number is a local variable in $.ready(), but it's used outside of this function
Ad 3
It's not valid JS (see #bipen's answer):
$(".nav_link").on('click')function(){
Ad 4
It's not valid if statement:
if (current_button.attr('id')) == 'next'
it should be:
if (current_button.attr('id') === 'next')
Ad 5
Use <script> tag only inside *.html file, not in *.js. On example:
<script src="main.js"></script>
Then, put all of your JS code into main.js file.

jQuery document ready buggyness with social sharing services

I have a strange issue that might have to do with jQuery document ready. Below is an html and script block that contains the usual social networking scripts. The Javascript block below displays the dd_outer div on the left edge of the body div, and when the browser window is shrunk, the div is faded out and the dd_footer div is faded in. The fadein and fadeout between the two divs works OK.
The problem is two fold: one issue is when the browser window is full width (1200px+), the Facebook script will not load and display consistently; it sometimes appears and sometimes doesn't, sometimes after a page reload and sometimes doesn't. (No browser or .htaccess caching is involved). Only the Facebook share fails to show consistently; all other services show OK.
The second problem that when the browser window is narrow - 650 px or so, when the dd_outer div is not displayed and the dd_footer div is - the footer div will not show on a page reload until the browser window is moved the smallest amount. Then the the div will display, Facebook share and all. For a mobile device, this is a problem because the browser window will be narrow to begin with and shouldn't need to be "nudged" to make the dd_footer div display.
This problem may have come into play because I have adapted this code from a WordPress plugin that used options to set the position of the dd_outer div and scroll height. That's the reason for the variables above the document ready call.
Is this the issue with what seems to be a document ready issue?
How can the variables be integrated into the script itself? It doesn't matter if they are hardcoded; I can change them when needed.
I'd throw this in a jsfiddle to demo but the divs won't realistically float with the window resizing.
I haven't included the CSS for clarity.
This is the html and social script block:
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'>
<div class="sbutton"><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like layout="box_count" show_faces="false" font=""></fb:like></div>
<div class="sbutton">
Tweet<script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div>
<div class="sbutton"><script type="text/javascript" src="https://apis.google.com/js/plusone.js"></script><g:plusone size="tall"></g:plusone></div>
<div class="sbutton"><script src="http://platform.linkedin.com/in.js" type="text/javascript"></script>
<script type="IN/Share" data-counter="top"></script></div>
</div></div></div>
In the footer is <div id="dd_footer">that contains the same social scripts as above</div> and are faded in and out by the script below:
This is the jQuery that positions the dd_outer social services to the left and fades it out and fades in the dd_footer div.
<script type="text/javascript">
var dd_top = 0;
var dd_left = 0;
var dd_offset_from_content = 70; var dd_top_offset_from_content = 10;
jQuery(document).ready(function(){
var $floating_bar = jQuery('#dd_ajax_float');
var $dd_start = jQuery('#dd_start');
var $dd_end = jQuery('#dd_end');
var $dd_outer = jQuery('.dd_outer');
// first, move the floating bar out of the content to avoid position: relative issues
$dd_outer.appendTo('body');
dd_top = parseInt($dd_start.offset().top) + dd_top_offset_from_content;
if($dd_end.length){
dd_end = parseInt($dd_end.offset().top);
}
dd_left = -(dd_offset_from_content + 55);
dd_adjust_inner_width();
dd_position_floating_bar(dd_top, dd_left);
$floating_bar.fadeIn('slow');
if($floating_bar.length > 0){
var pullX = $floating_bar.css('margin-left');
jQuery(window).scroll(function () {
var scroll_from_top = jQuery(window).scrollTop() + 30;
var is_fixed = $dd_outer.css('position') == 'fixed';
if($dd_end.length){
var dd_ajax_float_bottom = dd_end - ($floating_bar.height() + 30);
}
if($floating_bar.length > 0)
{
if(scroll_from_top > dd_ajax_float_bottom && $dd_end.length){
dd_position_floating_bar(dd_ajax_float_bottom, dd_left);
$dd_outer.css('position', 'absolute');
}
else if ( scroll_from_top > dd_top && !is_fixed )
{
dd_position_floating_bar(30, dd_left);
$dd_outer.css('position', 'fixed');
}
else if ( scroll_from_top < dd_top && is_fixed )
{
dd_position_floating_bar(dd_top, dd_left);
$dd_outer.css('position', 'absolute');
}
}
});
}
});
jQuery(window).resize(function() {
dd_adjust_inner_width();
});
var dd_is_hidden = false;
var dd_resize_timer;
function dd_adjust_inner_width() {
var $dd_inner = jQuery('.dd_inner');
var $dd_floating_bar = jQuery('#dd_ajax_float')
var width = parseInt(jQuery(window).width() - (jQuery('#dd_start').offset().left * 2));
$dd_inner.width(width);
var dd_should_be_hidden = (((jQuery(window).width() - width)/2) < -dd_left);
var dd_is_hidden = $dd_floating_bar.is(':hidden');
if(dd_should_be_hidden && !dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeOut(); }, -dd_left);
jQuery('#dd_footer').fadeIn();
}
else if(!dd_should_be_hidden && dd_is_hidden)
{
clearTimeout(dd_resize_timer);
dd_resize_timer = setTimeout(function(){ jQuery('#dd_ajax_float').fadeIn(); }, -dd_left);
jQuery('#dd_footer').fadeOut();
}
}
function dd_position_floating_bar(top, left, position) {
var $floating_bar = jQuery('#dd_ajax_float');
if(top == undefined) top = 0 + dd_top_offset_from_content;;
if(left == undefined) left = 0;
if(position == undefined) position = 'absolute';
$floating_bar.css({
position: position,
top: top + 'px',
left: left + 'px'
});
}
</script>
jQuery .ready() does not wait for iframes and other external media to load. These social buttons tend to work by inserting an iframe. The load event does wait for iframes etc, so you could try using that event instead, i.e.
jQuery(window).load(function () {
/* put the code you had inside .ready() here */
});
The problem comes with your idea: $(document).ready() fires when the DOM is ready, not when all scripts are ready!
an idea would be to search for trigger of that social-APIs you are using or just delay your calculations (e.g. via setTimeout).
Keep in mind that they are asyncron, even if you specify "async" on the script-tag to be false, you still dont know when they will activate or are finished.
I suggest to use the standard DOM event window.onload if you want to make sure that all the external assets, scripts, images, etc. are loaded first before you do something:
window.onload = function () {
// your script that needs to run after all the external assets are loaded
}
Reference: https://developer.mozilla.org/en-US/docs/DOM/window.onload
I just ran into similar problems with the facebook script... I just used the integration in the HEAD-section with javascript and added an "asynchronous"-attribute to the javascript-embedding script which then fires an asynchronous "heeey, facebook is ready now, too"-event to my jQuery-eventqueue...
I can't help you in detail, because I don't totally understand what you WANT to do and would reorganize the whole code A LOT... so - contact me private (email/skype) or try figuring out... I used that lines of code: pastie.org/private/9m4b9eet1dzzkl6duqpkrg

Javascript taking too long to load

The javascript of the div "intro" is loading at last. It's taking too long to load as the web page loads the bg image first and then loads the java script. Is there a way i can display "loading please wait" message in that "intro" div until it completely loads. I just want that the intro should load first.
Javascript code:
var tl = new Array(
"=======================",
" Welcome user, ",
" ###########################################"
);
var speed = 50;
var index = 0;
text_pos = 0;
var str_length = tl[0].length;
var contents, row;
function type_text() {
contents = '';
row = Math.max(0, index - 20);
while (row < index)
contents += tl[row++] + '\r\n';
document.forms[0].elements[0].value = contents + tl[index].substring(0, text_pos) + "_";
if (text_pos++ == str_length) {
text_pos = 0;
index++;
if (index != tl.length) {
str_length = tl[index].length;
setTimeout("type_text()", 500);
}
}
else setTimeout("type_text()", speed);
}
This is the script and its basically typing letter by letter in a text area in the div "intro". The problem is that it loads at last when the whole page has loaded. It starts printing the text after like 15 seconds or so.
There are "domready" events you can listen to on the document but seems that's not cross-browser.
Eg: Mozilla
document.addEventListener("DOMContentLoaded", methodName, false)
A better option is to use jQuery's .ready() event. They handle all cross-browser implementations.
Eg:
$(document).ready(function(){
//execute code here
});
//Shorthand
$(function(){
//...
});
See this related question for more on domready.
Load a page with the empty intro div, run the script with "loading please wait" then trigger an ajax request to load the rest of the page and update the page on onComplete event from the ajax request
Using jQuery
$(document).ready(function() {
// update div here
});
http://api.jquery.com/ready/
Or you could do that with
window.onload= (function() {
// update div here
};
You can use jquery for this by wrapping the content in a div tag and then another div that holds a loading image, something to this effect:
$(document).ready(function () {
$('#loading').show();
$('#divShowMeLater').load(function () {
$('#loading').hide();
$('#divShowMeLater').show();
});
})
Assume divShowMeLater is the div that contains all the content being loaded. The markup would look similiar to this:
<div id="divShowMeLater" style="margin-left:auto;margin-right:auto;text-align:center;" >
<div id="loading">Page loading...
<img src="images/ajax-loader.gif" alt="loading page..." />
</div>
</div>

Categories