Hi can anyone have a look at the below and tell me why its not working?
I am trying to get it all to create a popup box with a countdown timer and set a cookie so it doesn't do the popup box on every page. It's supposed to set a cookie and detect it and I think it's doing that but now the count down timer isn't visibly counting down.
$(document).ready(function() {
if(readCookie('oldsite') != 'stay') //Unless we find the cookie, we show the banner ...
{
var time_left = 12;
var cinterval;
cinterval = setInterval('time_dec()', 1000);
var id = '#dialog';
//Get the screen height and width
var maskHeight = $(document).height();
var maskWidth = $(window).width();
//Set heigth and width to mask to fill up the whole screen
$('#mask').css({'width':maskWidth,'height':maskHeight});
//transition effect
$('#mask').fadeIn(500);
$('#mask').fadeTo("slow",0.9);
//Get the window height and width
var winH = $(window).height();
var winW = $(window).width();
//Set the popup window to center
$(id).css('top', winH/2-$(id).height()/2);
$(id).css('left', winW/2-$(id).width()/2);
//transition effect
$(id).fadeIn(2000);
//if Disagree word is clicked
$('#disagree').click(function () {
$(this).hide();
$('.window').hide();
$('#mask').hide();
time_left = 0;
});
//if mask is clicked
$('#mask').click(function () {
createCookie('oldsite', 'stay', 1); //create the cookie for 1 day
$(this).hide();
$('.window').hide();
});
}
//Functions
function time_dec(){
time_left--;
document.getElementById('countdown').innerHTML = time_left;
if(time_left == 1){
var originalstring = document.getElementById('countdown2').innerHTML;
var newstring = originalstring.replace('seconds','second');
document.getElementById('countdown2').innerHTML = newstring;
window.location.replace("http://cadfemukandireland.com/");
clearInterval(cinterval);
}
}
function createCookie(name, value, days) {
var expires;
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
} else {
expires = "";
}
document.cookie = encodeURIComponent(name) + "=" + encodeURIComponent(value) + expires + "; path=/";
}
function readCookie(name) {
var nameEQ = encodeURIComponent(name) + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) === ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return decodeURIComponent(c.substring(nameEQ.length, c.length));
}
return null;
}
function eraseCookie(name) {
createCookie(name, "", -1);
}
});
The css is:
/* CSS Document */
#mask {
position: absolute;
left: 0;
top: 0;
z-index: 9000;
background-color: #000;
display: none;
}
#boxes .window {
position: absolute;
left: 0;
top: 0;
width: 440px;
height: 200px;
display: none;
z-index: 9999;
padding: 20px;
border-radius: 15px;
text-align: center;
}
#boxes #dialog {
width: 750px;
height: 300px;
padding: 75px 50px 10px 50px;
background-color: #ffffff;
font-family: 'Segoe UI Light', sans-serif;
font-size: 15pt;
}
#popupfoot {
font-size: 16pt;
position: absolute;
bottom: 0px;
width: 350px;
left: 225px;
padding-bottom:20px;
}
#disagree {
cursor:pointer;
}
and the html is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="boxes">
<div id="dialog" class="window">
<p>As part of our re branding to CADFEM, we have a new website</p>
<p>You will be redirected to the new website <span id="countdown2">in <span id="countdown">12</span> seconds</span>.</p>
<div id="popupfoot" style="padding-bottom:100px;"> If you wish to stay on the old website, please click <a id="disagree"><b><u>here</u></b></a>
</div>
</div>
<div id="mask"></div>
You can use Creative Tools
<div id="timer"></div>
<script>
$(document).ready(function(){
$("#timer").countdown({
duration : 30, // Discount start from defined number (in this case 30 seconds) DEFAULT: 0
interval : 1000, // interval in millisecond (DEFAULT: interval every 1000ms (1 second))
text_before : "Redirection begins in exactly ", // initial text before number (example: Redirection begins in exactly 30), DEFAULT: blank
text_after : "seconds" // initial text after number (example: 30seconds), DEFAULT: blank
},
// callback function when discount stop on 0
function(){
this.html("Done counting, redirecting.");
window.location = "http://www.google.com";
});
});
</script>
Also cookie function:
// Set a session cookie
$.cookie('the_cookie', 'the_value');
$.cookie('the_cookie'); // -> 'the_value'
// Set a cookie that expires in 7 days
$.cookie('the_cookie', 'the_value', { expires: 7 });
// delete the cookie
$.cookie('the_cookie', null);
You can copy this 2 functions and integrate with your code or use whole creative tools.
Also you can use Local Storage function what if storage is disabled or not exist use cookie:
// Set a session storage
$.storage('the_name', 'the_value');
// Get session storage
$.storage('the_name');
// delete storage
$.storage('the_name', null);
You counter is not working because you are parsing your time_dec function as a string
cinterval = setInterval('time_dec()', 1000);
remove the comma's and the () and you should be fine
cinterval = setInterval(time_dec, 1000);
See working jsfiddle here https://jsfiddle.net/domjgreen/zngLk99q/
Related
For teaching myself javascript (and for getting/giving more insight in the field of astronomy :) ), I am setting up a page that displays relative positions of sun and moon.
Right now, the speed of the sun and moon movement is still fixed, but I would really like to make this dynamically user-definable via an input field. So, the initial speed is '30', and a user can speed this up or slow this down. Obviously, the ratio between sun and moon must stay fixed. I tried a lot of things (see some relics in the code, but I can't get it to work.
Anyone with more experience with javascript can assist me in doing this? Also, I notice CPU usage gets very high during this animation. Are there simple steps in making this script more efficient?
var dagen = 0;
function speed($this){
var speedSetting = $this.value;
//alert(speedSetting);
//return per;
}
function periode(bolletje, multiplier=30){
if (bolletje == 'zon'){var per = (multiplier*24/2);}
if (bolletje == 'maan'){var per = (multiplier*24*29.5/2);}
return per;
}
function step(delta) {
elem.style.height = 100*delta + '%'
}
function animate(opts) {
var start = new Date
var id = setInterval(function() {
var timePassed = new Date - start
var progress = timePassed / opts.duration
if (progress > 1) progress = 1
var delta = opts.delta(progress)
opts.step(delta)
if (progress == 1) {
clearInterval(id)
}
}, opts.delay || 10)
}
function terugweg(element, delta, duration) {
var to = -300;
var bolletje = element.getAttribute('id');
per = periode(bolletje);
document.getElementById(bolletje).style.background='transparent';
animate({
delay: 0,
duration: duration || per,
//1 sec by default
delta: delta,
step: function(delta) {
element.style.left = ((to*delta)+300) + "px"
}
});
if(bolletje == 'zon'){
dagen ++;
}
bolletje = element;
document.getElementById('dagen').innerHTML = dagen;
//setInterval(function (element) {
setTimeout(function (element) {
move(bolletje, function(p) {return p})
}, per);
}
function move(element, delta, duration) {
var to = 300;
var bolletje = element.getAttribute('id');
per = periode(bolletje);
document.getElementById(bolletje).style.background='yellow';
animate({
delay: 0,
duration: duration || per,
//1 sec by default
delta: delta,
step: function(delta) {
element.style.left = to*delta + "px"
}
});
bolletje = element;
//setInterval(function (element) {
setTimeout(function (element) {
terugweg(bolletje, function(p) {return p})
}, per);
}
hr{clear: both;}
form{display: block;}
form label{width: 300px; float: left; clear: both;}
form input{float: right;}
.aarde{width: 300px; height: 300px; border-radius: 150px; background: url('https://domain.com/img/aarde.png');}
#zon{width: 40px; height: 40px; background: yellow; border: 2px solid yellow; border-radius: 20px; position: relative; margin-left: -20px; top: 120px;}
#maan{width: 30px; height: 30px; background: yellow; border: 2px solid yellow; border-radius: 16px; position: relative; margin-left: -15px; top: 115px;}
<form>
<div onclick="move(this.children[0], function(p) {return p}), move(this.children[1], function(p) {return p})" class="aarde">
<div id="zon"></div>
<div id="maan"></div>
</div>
Dagen: <span id="dagen">0</span>
</form>
<form>
<label><input id="snelheid" type="range" min="10" max="300" value="30" oninput="speed(this)">Snelheid: <span id="snelheidDisplay">30</span></label>
</form>
First, change onlick to oninput in speed input tag.
<input id="snelheid" type="number" value="30" oninput="speed(this)">
And in your speed() function set multiplier = $this.value. multiplier should be global:
var multiplier = 30;
function speed($this){
console.log($this.value);
multiplier = $this.value;
//alert(speedSetting);
//return per;
}
function periode(bolletje){
if (bolletje == 'zon'){var per = (multiplier*24/2);}
if (bolletje == 'maan'){var per = (multiplier*24*29.5/2);}
return per;
}
Here is an example:
https://jsfiddle.net/do4n9L03/2/
Note: multiplier is not speed, it is delay. If you increase it it become slower
I got a really great script found here : http://beeker.io/exit-intent-popup-script-tutorial
Here is the js (bioep.js) code :
window.bioEp = {
// Private variables
bgEl: {},
popupEl: {},
closeBtnEl: {},
shown: false,
overflowDefault: "visible",
transformDefault: "",
// Popup options
width: 400,
height: 220,
html: "",
css: "",
fonts: [],
delay: 1,
showOnDelay: false,
cookieExp: 1,
cookieManager: {
// Create a cookie
create: function(name, value, days) {
var expires = "";
if(days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
expires = "; expires=" + date.toGMTString();
}
document.cookie = name + "=" + value + expires + "; path=/";
},
// Get the value of a cookie
get: function(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(";");
for(var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == " ") c = c.substring(1, c.length);
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length, c.length);
}
return null;
},
// Delete a cookie
erase: function(name) {
this.create(name, "", -1);
}
},
// Handle the bioep_shown cookie
// If present and true, return true
// If not present or false, create and return false
checkCookie: function() {
// Handle cookie reset
if(this.cookieExp <= 0) {
this.cookieManager.erase("bioep_shown");
return false;
}
// If cookie is set to true
if(this.cookieManager.get("bioep_shown") == "true")
return true;
// Otherwise, create the cookie and return false
this.cookieManager.create("bioep_shown", "true", this.cookieExp);
return false;
},
// Add font stylesheets and CSS for the popup
addCSS: function() {
// Add font stylesheets
for(var i = 0; i < this.fonts.length; i++) {
var font = document.createElement("link");
font.href = this.fonts[i];
font.type = "text/css";
font.rel = "stylesheet";
document.head.appendChild(font);
}
// Base CSS styles for the popup
var css = document.createTextNode(
"#bio_ep_bg {display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: #000; opacity: 0.3; z-index: 10001;}" +
"#bio_ep {display: none; position: fixed; width: " + this.width + "px; height: " + this.height + "px; font-family: 'Titillium Web', sans-serif; font-size: 16px; left: 50%; top: 50%; transform: translateX(-50%) translateY(-50%); -webkit-transform: translateX(-50%) translateY(-50%); -ms-transform: translateX(-50%) translateY(-50%); background-color: #fff; box-shadow: 0px 1px 4px 0 rgba(0,0,0,0.5); z-index: 10002;}" +
"#bio_ep_close {position: absolute; left: 100%; margin: -8px 0 0 -12px; width: 20px; height: 20px; color: #fff; font-size: 12px; font-weight: bold; text-align: center; border-radius: 50%; background-color: #5c5c5c; cursor: pointer;}" +
this.css
);
// Create the style element
var style = document.createElement("style");
style.type = "text/css";
style.appendChild(css);
// Insert it before other existing style
// elements so user CSS isn't overwritten
document.head.insertBefore(style, document.getElementsByTagName("style")[0]);
},
// Add the popup to the page
addPopup: function() {
// Add the background div
this.bgEl = document.createElement("div");
this.bgEl.id = "bio_ep_bg";
document.body.appendChild(this.bgEl);
// Add the popup
if(document.getElementById("bio_ep"))
this.popupEl = document.getElementById("bio_ep");
else {
this.popupEl = document.createElement("div");
this.popupEl.id = "bio_ep";
this.popupEl.innerHTML = this.html;
document.body.appendChild(this.popupEl);
}
// Add the close button
this.closeBtnEl = document.createElement("div");
this.closeBtnEl.id = "bio_ep_close";
this.closeBtnEl.appendChild(document.createTextNode("X"));
this.popupEl.insertBefore(this.closeBtnEl, this.popupEl.firstChild);
},
// Show the popup
showPopup: function() {
if(this.shown) return;
this.bgEl.style.display = "block";
this.popupEl.style.display = "block";
// Handle scaling
this.scalePopup();
// Save body overflow value and hide scrollbars
this.overflowDefault = document.body.style.overflow;
document.body.style.overflow = "hidden";
this.shown = true;
},
// Hide the popup
hidePopup: function() {
this.bgEl.style.display = "none";
this.popupEl.style.display = "none";
// Set body overflow back to default to show scrollbars
document.body.style.overflow = this.overflowDefault;
},
// Handle scaling the popup
scalePopup: function() {
var margins = { width: 40, height: 40 };
var popupSize = { width: bioEp.popupEl.offsetWidth, height: bioEp.popupEl.offsetHeight };
var windowSize = { width: window.innerWidth, height: window.innerHeight };
var newSize = { width: 0, height: 0 };
var aspectRatio = popupSize.width / popupSize.height;
// First go by width, if the popup is larger than the window, scale it
if(popupSize.width > (windowSize.width - margins.width)) {
newSize.width = windowSize.width - margins.width;
newSize.height = newSize.width / aspectRatio;
// If the height is still too big, scale again
if(newSize.height > (windowSize.height - margins.height)) {
newSize.height = windowSize.height - margins.height;
newSize.width = newSize.height * aspectRatio;
}
}
// If width is fine, check for height
if(newSize.height === 0) {
if(popupSize.height > (windowSize.height - margins.height)) {
newSize.height = windowSize.height - margins.height;
newSize.width = newSize.height * aspectRatio;
}
}
// Set the scale amount
var scaleTo = newSize.width / popupSize.width;
// If the scale ratio is 0 or is going to enlarge (over 1) set it to 1
if(scaleTo <= 0 || scaleTo > 1) scaleTo = 1;
// Save current transform style
if(this.transformDefault === "")
this.transformDefault = window.getComputedStyle(this.popupEl, null).getPropertyValue("transform");
// Apply the scale transformation
this.popupEl.style.transform = this.transformDefault + " scale(" + scaleTo + ")";
},
// Event listener initialisation for all browsers
addEvent: function (obj, event, callback) {
if(obj.addEventListener)
obj.addEventListener(event, callback, false);
else if(obj.attachEvent)
obj.attachEvent("on" + event, callback);
},
// Load event listeners for the popup
loadEvents: function() {
// Track mouseout event on document
this.addEvent(document, "mouseout", function(e) {
e = e ? e : window.event;
var from = e.relatedTarget || e.toElement;
// Reliable, works on mouse exiting window and user switching active program
if(!from || from.nodeName === "HTML")
bioEp.showPopup();
});
// Handle the popup close button
this.addEvent(this.closeBtnEl, "click", function() {
bioEp.hidePopup();
});
// Handle window resizing
this.addEvent(window, "resize", function() {
bioEp.scalePopup();
});
},
// Set user defined options for the popup
setOptions: function(opts) {
this.width = (typeof opts.width === 'undefined') ? this.width : opts.width;
this.height = (typeof opts.height === 'undefined') ? this.height : opts.height;
this.html = (typeof opts.html === 'undefined') ? this.html : opts.html;
this.css = (typeof opts.css === 'undefined') ? this.css : opts.css;
this.fonts = (typeof opts.fonts === 'undefined') ? this.fonts : opts.fonts;
this.delay = (typeof opts.delay === 'undefined') ? this.delay : opts.delay;
this.showOnDelay = (typeof opts.showOnDelay === 'undefined') ? this.showOnDelay : opts.showOnDelay;
this.cookieExp = (typeof opts.cookieExp === 'undefined') ? this.cookieExp : opts.cookieExp;
},
// Ensure the DOM has loaded
domReady: function(callback) {
(document.readyState === "interactive" || document.readyState === "complete") ? callback() : this.addEvent(document, "DOMContentLoaded", callback);
},
// Initialize
init: function(opts) {
// Handle options
if(typeof opts !== 'undefined')
this.setOptions(opts);
// Add CSS here to make sure user HTML is hidden regardless of cookie
this.addCSS();
// Once the DOM has fully loaded
this.domReady(function() {
// Handle the cookie
if(bioEp.checkCookie()) return;
// Add the popup
bioEp.addPopup();
// Load events
setTimeout(function() {
bioEp.loadEvents();
if(bioEp.showOnDelay)
bioEp.showPopup();
}, bioEp.delay * 1000);
});
}
}
And here is the HTML code:
<script type="text/javascript" src="bioep.js"></script>
<script type="text/javascript">
bioEp.init({
html: '<div id="#leaving-content">The content i want to print</div>',
css: '#leaving-content {padding: 5%;}'});
</script>
This script allow to open a pop-up when user try to leave the page. Pretty nice work. But i'm a great noob and for a personnal project i try to adapt this code to be able to run a pop-under with an another website inside an not only my own html code (like an iframe). Can you help me please ?
Thank you !
No need for such scripts if you only want it to work for the back button, here's some simple code to do the job (requires jQuery).
var popupWebsite = "http://seapip.com";
if (window.history && window.history.pushState) {
window.history.pushState('forward', null, './');
}
$(window).on('popstate', function() {
$("html").append("<iframe src="+popupWebsite +" style=\"position: fixed; top: 0; left: 0; width: 100%; height: 100%;\"></iframe>")
});
I am trying to make a script that if you've never visited the site before, it will redirect to /agree.htm where if they click okay it wont ask again, but if they don't click it will keep redirecting to the /agree.htm page.
Here's the JavaScript so far:
function doit() {
document.getElementById('uuid').innerHTML = generateUUID();
var yes = getUrlVars()["agreed"];
if (yes == "true") {setCookie('VisitDate',1,365); }
if (yes != "true") {window.location = "/agree.htm";}
}
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function getCookie(NameOfCookie){
if (document.cookie.length > 0) {
begin = document.cookie.indexOf(NameOfCookie+"=");
if (begin != -1) {
begin += NameOfCookie.length+1;
end = document.cookie.indexOf(";", begin);
if (end == -1) end = document.cookie.length;
return unescape(document.cookie.substring(begin, end));
}
}
return null;
}
function setCookie(NameOfCookie, value, expiredays) {
var ExpireDate = new Date();
ExpireDate.setTime(ExpireDate.getTime() + (expiredays * 24 * 3600 * 1000));
document.cookie = NameOfCookie + "=" + escape(value) +
((expiredays == null) ? "" : "; expires=" + ExpireDate.toGMTString());
}
function delCookie (NameOfCookie) {
if (getCookie(NameOfCookie)) {
document.cookie = NameOfCookie + "=" +
"; expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
function DoTheCookieStuff(LastChangeDate)
{
dt=new Date();
year=dt.getYear(); if (year<=9) {year="0"+year};
month=dt.getMonth()+1; if (month<=9) {month="0"+month};
date=dt.getDate(); if (date<=9) {date="0"+date};
ThisDate=year+month+date;
LastVisitDate=getCookie('VisitDate');
if (LastVisitDate!=null)
{ if (LastVisitDate<LastChangeDate) {}
else {}
setCookie('VisitDate',ThisDate,365)
}
else {window.location = "\agree.htm";}
}
It sets the cookie but will keep redirecting to the /agree.htm page.
AGREE.HTM:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>StratHaxxs Co. ToS Agreement</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<style>
.ui-dialog-titlebar-close {
visibility: hidden;
}
.ui-widget.success-dialog {
font-family: Verdana,Arial,sans-serif;
font-size: .8em;
}
.ui-widget-content.success-dialog {
background: #F9F9F9;
border: 1px solid #90d93f;
color: #222222;
}
.ui-dialog.success-dialog {
left: 0;
outline: 0 none;
padding: 0 !important;
position: absolute;
top: 0;
}
.ui-dialog.success-dialog .ui-dialog-content {
background: none repeat scroll 0 0 transparent;
border: 0 none;
overflow: auto;
position: relative;
padding: 0 !important;
margin: 0;
}
.ui-dialog.success-dialog .ui-widget-header {
background: #b0de78;
border: 0;
color: #fff;
font-weight: normal;
}
.ui-dialog.success-dialog .ui-dialog-titlebar {
padding: 0.1em .5em;
position: relative;
font-size: 1em;
}
.ui-dialog .ui-dialog-buttonpane {
text-align: center;
}
.ui-dialog .ui-dialog-buttonpane .ui-dialog-buttonset {
float: none;
}
</style>
<script>
$(function() {
$('#success').dialog({
height: 180,
width: 350,
modal: true,
resizable: false,
dialogClass: 'no-close success-dialog',
buttons: {
Ok: function() {
$( this ).dialog( "close" );
window.location.href = "/?agreed=true";
}
}
});
});
</script>
</head>
<body>
<div id="success" title="Welcome!">
<p>
This is the first time you have visited our site, to continue to the site:
Click 'Ok' if you agree to our <b>ToS</b>: Here<br><br>Otherwise press the back button or close this window.
</p>
</div>
</body>
</html>
Working Demo
It looks like you had all the right functions listed in your Javascript, but they weren't being called.
On page load you want to check if the cookie is present. If not, then you'll want to show the jQuery Dialog modal.
I added a button to remove the cookie so you can test.
Remove the Javascript from your <script> tag and replace it with this:
Javascript
$( document ).ready(function() {
$('#remove-cookie').click(function() {
delCookie('agreeCookie');
$('h1').text('Cookie Removed');
$('#remove-cookie').hide();
});
var cookieStatus = getCookie('agreeCookie');
console.log(cookieStatus);
if (cookieStatus != 'true') {
tryRedirect('agree.htm');
$('#success').show().dialog({
height: 180,
width: 350,
modal: true,
resizable: false,
dialogClass: 'no-close success-dialog',
buttons: {
Ok: function () {
setCookie('agreeCookie', true, 100);
$(this).dialog("close");
window.location.href = "index.html?agreed=true";
}
}
});
}
else {
tryRedirect('index.html');
$('#remove-cookie').show();
}
function tryRedirect(target) {
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/') + 1);
if (filename != target) {
window.location.href = target;
}
}
});
To Test
Open the Demo and click Ok in the dialog (this will add the cookie).
Reload the page. The cookie should be present and you'll be redirected to index.html and shown the Remove cookie button (repeat this step as much as you want and it should still do this).
Press the Remove cookie button and reload again. Now it should redirect to agree.htm and show the dialog again.
I have to have two images start on the left side of the screen and move to the right side and stop. Its like a race and whoever get to the right side first wins. I am generating a random number for this just, the images only move to the right once. I cant figure out why they are only moving once, and dont know how I would get them to stop on the right side.
Here's my code:
var myVar1 = setInterval(fly, 250);
function fly() {
var ranNum = Math.floor(Math.random()*2);
if(ranNum == 0){
document.getElementById("race").style.left = '25px';
} else if (ranNum == 1){
document.getElementById("race1").style.left = "25px";
}
}
body { background-image: url(images/stars.jpg); }
.img1 {
position: absolute;
bottom: 0px;
left: 0px;
}
.img2 {
position: absolute;
bottom: 200px;
left: 0px;
}
.img3 {
position: absolute;
top: 0px;
right: 0px;
}
<img src="images/tie.png" class="img1" id="race" alt="tie"></br>
<img src="images/xwing.png" class="img2" id="race1" alt="xwing">
<img src="images/death.png" class="img3" alt="dstar">
The third image(death.png aka death star), when its clicked it changes color and starts the "race" which I would use the onClick method for that, right? So once either the tie fighter or x-wing reaches the "finish line" on the right side, both images stop so we will have a winner. Also if the x-wing wins, I am going to have the dstar change to a dstar blowing up.
You need to increment the values in order to get it to move.
var leftIncrement = parseInt(document.getElementById("race").style.left) + ranNum + "px";
document.getElementById("race").style.left = leftIncrement;
At the moment you are setting it to "25px" every interval.
Try this:
var els = [document.getElementById("race"), document.getElementById("race1")],
timer = setInterval(fly, 250);
function fly() {
var el = els[Math.floor(Math.random()*2)],
newPos = (parseInt(el.style.left) || 0) + 1;
el.style.left = newPos + 'px';
if(newPos == 25) {
clearInterval(timer);
el.classList.add('winner');
}
}
var els = [document.getElementById("race"), document.getElementById("race1")],
timer = setInterval(fly, 250);
function fly() {
var el = els[Math.floor(Math.random()*2)],
newPos = (parseInt(el.style.left) || 0) + 1;
el.style.left = newPos + 'px';
if(newPos == 25) {
clearInterval(timer);
el.classList.add('winner');
}
}
body { background-image: url(images/stars.jpg); }
.img1 {
position: absolute;
bottom: 0px;
left: 0px;
}
.img2 {
position: absolute;
bottom: 200px;
left: 0px;
}
.img3 {
position: absolute;
top: 0px;
right: 0px;
}
.winner {
outline: 3px solid #0f0;
}
<img src="images/tie.png" class="img1" id="race" alt="tie"></br>
<img src="images/xwing.png" class="img2" id="race1" alt="xwing">
<img src="images/death.png" class="img3" alt="dstar">
It's because regardless of what random numbers you are generating, you are always assigned a left style value of 25px.
var left = document.getElementById("race").style.left;
left = left.replace('px','');
left += parseInt(left) + 25;
document.getElementById("race").style.left = left + "px";
Untested but should work.
This works
var racers = [ document.getElementById("race"), document.getElementById("race1") ];
var interval = setInterval( fly, 250 );
function fly() {
var racer = racers[ Math.floor(Math.random() * racers.length) ];
var newPos = parseInt( racer.style.left || 0 ) + 25;
racer.style.left = newPos + "px";
if( (newPos + racer.clientWidth) >= window.innerWidth){
clearInterval( interval );
alert( "And the winner is " + racer.id );
}
}
Here you got it in a JsFiddle http://jsfiddle.net/5poa7tnt/10/
Ask if you need help to understand
Edit : Looks similar to Oriol's post thought
Edit 2 : The race is most beautiful the a step of "1" instead of "25" and an interval of "5" or "10" instead of 250 .. I don't know what final result you want
The slider should function nice and smooth. Instead the animation isn't working smoothly. Here are the HTML, CSS and Javascript. I looked and looked and looked and can't find the clue. Rotating is not smooth, caption does not match the image, the last image doesn't even appear. (Here is the actual demo).
Here are some sample images showing a bit of the problem:
<IMG ID="slideshowPicturePlaceholder" src="/_layouts/images/GEARS_AN.GIF" style="display:none"/>
<div id="slideshowContentArea" style="display:none; width:255px;">
<div class="main_view">
<div class="window">
<div class="image_reel"> </div>
</div>
<div class="paging">
1
2
3
4
</div>
</div>
</div>
<style type="text/css">
/*--Main Container--*/
.main_view {
float: left;
position: relative;
}
/*--Window/Masking Styles--*/
.window {
height: 286px; width: 790px;
overflow: hidden; /*--Hides anything outside of the set width/height--*/
position: relative;
}
.image_reel {
position: absolute;
top: 0; left: 0;
}
.image_reel img {float: left;}
/*--Paging Styles--*/
.paging {
position: absolute;
bottom: 40px; right: -7px;
width: 178px; height:47px;
z-index: 100; /*--Assures the paging stays on the top layer--*/
text-align: center;
line-height: 40px;
background: url(paging_bg2.png) no-repeat;
display: none; /*--Hidden by default, will be later shown with jQuery--*/
}
.paging a {
padding: 5px;
text-decoration: none;
color: #fff;
}
.paging a.active {
font-weight: bold;
background: #920000;
border: 1px solid #610000;
-moz-border-radius: 3px;
-khtml-border-radius: 3px;
-webkit-border-radius: 3px;
}
.paging a:hover {font-weight: bold;}
</style>
<script type="text/javascript" src="_layouts/jquery/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="_layouts/jquery/jquery.cycle.all.js"></script>
<script type="text/javascript">
$(document).ready(function() {
function GetAllImages()
{
$("#slideshowPicturePlaceholder").css("display", "block");
var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>";
soapEnv += "<listName>NewsRotator</listName>";
soapEnv += "<query><Query><OrderBy Override='TRUE'><FieldRef Name='Created' Ascending='FALSE' /></OrderBy></Query></query>";
soapEnv += "<viewFields><ViewFields><FieldRef Name='Title'/><FieldRef Name='ows_FileLeafRef'/><FieldRef Name='NewsLink'/><FieldRef Name='Description'/></ViewFields></viewFields><rowLimit></rowLimit>";
soapEnv += "</GetListItems></soapenv:Body></soapenv:Envelope>";
var port = window.location.port;
if (port.length <= 0)
port = "";
else
port = ":" + port;
var webservice = window.location.protocol + "//" + window.location.hostname + port + L_Menu_BaseUrl + "/_vti_bin/lists.asmx";
$.ajax(
{
url : webservice,
type : "POST",
dataType : "xml",
data : soapEnv,
complete : processQueryResults,
contentType : "text/xml; charset=utf-8",
error : function (xhr)
{
alert('Error! Status = ' + xhr.status);
}
});
}
function processQueryResults(xData, status)
{
var port = window.location.port;
if (port.length <= 0)
port = "";
else
port = ":" + port;
// Change the below to point to your image library
var imageURL = window.location.protocol + "//" + window.location.hostname + port + L_Menu_BaseUrl + "/Splash Image Rotator/";
var itemURL = window.location.protocol + "//" + window.location.hostname + port + L_Menu_BaseUrl + "/Splash Image Rotator/Forms/DispForm.aspx?ID=";
// $("#slideshowContentArea").html("")
$(xData.responseXML).find("z\\:row").each(function ()
{
var title = $(this).attr("ows_Title");
var headlines = $(this).attr("ows_Description");
var imageLink = imageURL + $(this).attr("ows_FileLeafRef").substring($(this).attr("ows_FileLeafRef").indexOf('#') + 1);
// // var itemLink = itemURL + $(this).attr("ows_ID");
var itemLink = $(this).attr("ows_NewsLink");
//var liHtml = "<div><a href='" + itemLink + "' target='_blank'><img src='" + imageLink + "'/></a></div>";
//var liHtml ="<a target='_blank' border='0' href='"+itemLink+"'><img src='"+ imageLink +"'/></a>";
var liHtml = "<a href='"+itemLink+"' target='_blank' border='0'><img src='" + imageLink +"'/></a><p>"+ title + " - " + headlines + "</p>";
$(".image_reel").append(liHtml);
});
$("#slideshowPicturePlaceholder").css("display", "none");
$("#slideshowContentArea").css("display", "block");
// Show the paging and activate its first link
$(".paging").show();
$(".paging a:first").addClass("active");
// Get size of the image, how many images there are, then determin the size of the image reel.
var imageWidth = $(".window").width();
var imageSum = $(".image_reel img").size();
var imageReelWidth = imageWidth * imageSum;
// Adjust the image reel to its new size
$(".image_reel").css(
{
'width' : imageReelWidth
}
);
// Paging and Slider Function
rotate = function ()
{
var triggerID = $active.attr("rel") - 1;
// Get number of times to slide
var image_reelPosition = triggerID * imageWidth;
// Determines the distance the image reel needs to slide
$(".paging a").removeClass('active');
// Remove all active class
$active.addClass('active');
// Add active class (the $active is declared in the rotateSwitch function)
// Slider Animation
$(".image_reel").animate(
{
left : - image_reelPosition
}
, 500);
}
;
// Rotation and Timing Event
rotateSwitch = function ()
{
play = setInterval(function ()
{
// Set timer - this will repeat itself every 7 seconds
$active = $('.paging a.active').next();
// Move to the next paging
if ($active.length === 0)
{
// If paging reaches the end...
$active = $('.paging a:first');
// go back to first
}
rotate();
// Trigger the paging and slider function
}
, 3000);
// Timer speed in milliseconds (7 seconds)
}
;
rotateSwitch();
// Run function on launch
// On Hover
$(".image_reel a").hover(function ()
{
clearInterval(play);
// Stop the rotation
}
, function ()
{
rotateSwitch();
// Resume rotation timer
} );
// On Click
$(".paging a").click(function ()
{
$active = $(this);
// Activate the clicked paging
// Reset Timer
clearInterval(play);
// Stop the rotation
rotate();
// Trigger rotation immediately
rotateSwitch();
// Resume rotation timer
return false;
// Prevent browser jump to link anchor
}
);
}
GetAllImages();
});
</script>
This issue might cause because of using position property in CSS.
position absolute is not necessary for '.image_reel' class, try with float:left.
Is this question still active? try to remove absolute position from your "image_reel" class