Countdown bar Javascript not decreasing - javascript

I have this JS code for a countdown progress bar that should take a time value and decrease until time is reached, then display EXPIRED.
function progress(timeleft, timetotal, $element) {
var bar = document.getElementById("#progressBar")
var progressBarWidth = (timeleft * bar.width()) / timetotal
console.log("width is" + bar.width() + "time left is" + timeleft)
$element.find("div").animate({
width: progressBarWidth
}, timeleft == timetotal ? 0 : 1000, "linear")
if (timeleft > 0) {
setTimeout(function() {
progress(timeleft - 1, timetotal, $element)
}, 1000)
}
}
progress(180, 180, $("#progressBar"))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="progressBar">
<div></div>
</div>
Problem is that here I set it to 3min for testing and bar doesn't decrease. I've debugged via console and 'bar.width()' seems to be undefined. Any ideas how to fix it? Thanks!

SHouldn't this
var bar = document.getElementById("#progressBar")
be this
var bar = document.getElementById("progressBar")
https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
and
bar.width()
be
bar.clientWidth
https://developer.mozilla.org/en-US/docs/Web/API/Element

You are already passing in the $element, which IS bar.
function progress(timeleft, timetotal, $element) {
var progressBarWidth = (timeleft * $element.width()) / timetotal
console.log(`width: ${$element.width()} px | time left: ${timeleft} sec`)
$element.find("div").animate({
width: progressBarWidth
}, timeleft == timetotal ? 0 : 1000, "linear")
if (timeleft > 0) {
setTimeout(progress, 1000, timeleft - 1, timetotal, $element)
}
}
progress(60, 60, $("#progressBar"))
#progressBar div {
background: green;
height: 1em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="progressBar">
<div></div>
</div>
Note: You can invoke setTimeout without creating a nested function call. The parameters following the timeout (2nd param) will be passed into the callback function.
Replace this:
if (timeleft > 0) {
setTimeout(function() {
progress(timeleft - 1, timetotal, $element)
}, 1000)
}
With this:
if (timeleft > 0) {
setTimeout(progress, 1000, timeleft - 1, timetotal, $element)
}
jQuery plugin!
Here is a jQuery plugin version
(($) => {
const init = ($bar) => {
if ($bar.find('div').length === 0) $bar.append($('<div>'));
}
const run = ($bar, duration, timeRemaining, callback) => {
update($bar, duration, timeRemaining)
if (timeRemaining > 0) {
setTimeout(tick, 1000, $bar, duration, timeRemaining, callback)
} else {
callback()
}
}
const update = ($bar, duration, timeRemaining) => {
const width = (timeRemaining * $bar.width()) / duration
$bar.find('div').animate({
width: width
}, timeRemaining == duration ? 0 : 1000, 'linear')
}
const tick = ($bar, duration, timeRemaining, callback) => {
run($bar, duration, timeRemaining - 1, callback)
}
$.fn.progress = function(duration, timeRemaining, callback) {
init(this)
run(this, duration, timeRemaining, callback);
return this
}
})(jQuery);
$('#progress-bar-1').progress(10, 10, () => {
console.log('Task #1 completed!')
})
$('#progress-bar-2').progress(5, 5, () => {
console.log('Task #2 completed!')
})
div[id^="progress-bar"] div {
background: green;
height: 1em;
margin-bottom: 0.5em;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="progress-bar-1"></div>
<div id="progress-bar-2"></div>

Related

How to create a progress timer based on two dates in javascript

My goal is to create a progress bar that shows a countdown in seconds between one Javascript date and one MYSQL date. So far I have the dates and can subtract them, but I can't get a value that works in seconds for the progress bar. here is my code. Creation date is from a MYSQL datetime.
JAVASCRIPT
$(document).ready(function(){
var deadline= new Date(Date.parse("<? echo $creation_date; ?>"));
var x = setInterval(function() {
var now = Date.now();
var timeleft = deadline - now;
if (timeleft < 0) {
clearInterval(x);
timeleft = 0;
}, 1000);
// draw the bar
function progress(timeleft, timetotal, $element) {
var progressBarWidth = timeleft * $element.width() / timetotal;
$element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear');
if(timeleft > 0) {
setTimeout(function() {
progress(timeleft - 1, timetotal, $element);
}, 1000);
}
};
// 86400 is 24 hours.
progress(timeleft, 86400, $('#timerBar'));
HTML
<div id="timerBar">
<div>Time Left</div>
</div>
CSS
#timerBar {
width: 90%;
margin: 10px auto;
height: 30px;
background-color: #efd0d0;
}
#timerBar div {
height: 100%;
text-align: right;
padding: 0 30px;
line-height: 22px;
width: 0;
background-color: #d05656;
box-sizing: border-box;
}

Logout with a countdown progress bar

I am using the code from here to logout users after idle time (when no click is received anywhere on the body). I am trying to combine that with a countdown progress bar here
My Code below
#timeouts {
display: none;
}
#progressBar {
width: 100%;
margin: 10px auto;
height: 22px;
background-color: red;
}
#progressBar div {
height: 100%;
text-align: right;
padding: 0 10px;
line-height: 22px; /* same as #progressBar height if we want text middle aligned */
width: 0;
background-color: yellow;
box-sizing: border-box;
}
HTML
<body class="smoothscroll boxed pattern7 printable" onload="StartTimers();" onclick="ResetTimers();">
<div id="progressBar"><div></div></div>
<div id="timeouts">
<h2>Session About To Timeout</h2>
<span class="alert alert-warning">Alert! Logout in 4 Seconds</span>
</div>
</body>
JS
var timoutWarning = 10000; // Displa
var timoutNow = 14000; // Time
var logoutUrl = '/logout'; //
var warningTimer;
var timeoutTimer;
// Start timers.
function StartTimers() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(timeoutTimer);
StartTimers();
document.getElementById("timeouts").style.display = "none";
progress(14, 14, $('#progressBar')); //This makes things go crazy
}
// Show idl
function IdleWarning() {
document.getElementById("timeouts").style.display = "block";
}
// Logout the user.
function IdleTimeout() {
window.location = logoutUrl;
}
function progress(timeleft, timetotal, $element) {
var progressBarWidth = timeleft * $element.width() / timetotal;
$element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear').html(timeleft+ " s");
if (timeleft > 0) {
setTimeout(function () {
progress(timeleft - 1, timetotal, $element);
}, 1000);
}
};
progress(14, 14, $('#progressBar'));
It will work perfectly on page load. But when the function ResetTimers() is called, it is supposed to reset the progress function. But things go crazy with the progress bar showing random values. Please help me figure out what is going on.
I solved it like this.
var timoutWarning = 1140000; // Display warning after 19 minutes
var logoutUrl = '/logout'; //
var warningTimer;
var timeoutTimer;
var progressTimer;
var timeleft = 1200;
var timetotal = 1200;
// Start timers.
function StartTimers() {
warningTimer = setTimeout("IdleWarning()", timoutWarning);
progress(timeleft, timetotal, $('#progressBar'));
}
// Reset timers.
function ResetTimers() {
clearTimeout(warningTimer);
clearTimeout(progressTimer);
StartTimers();
document.getElementById("timeouts").style.display = "none";
}
// Show idl
function IdleWarning() {
document.getElementById("timeouts").style.display = "block";
}
// Logout the user.
function IdleTimeout() {
window.location = logoutUrl;
}
function progress(timeleft, timetotal, $element) {
var progressBarWidth = timeleft * 100 / timetotal;
$element.find('div').animate({ width: progressBarWidth }, timeleft == timetotal ? 0 : 1000, 'linear').html((timeleft / 60).toFixed(1) + " m");
if (timeleft > 0) {
progressTimer = setTimeout(function () { progress(timeleft - 1, timetotal, $element); }, 1000);
}
else {
IdleTimeout();
}
};
By assigning a variable to the setTimeout function call inside my recursive function and then clear it by clearTimeout(progressTimer) inside the ResetTimers() call. Thank you

How to not increase setInterval then called several times

Is there is possibility to not increase set interval speed after calling it several times. I'm doing the auto scroll function. After you hit the selected speed button it calls the function setInterval. My problem that more I hit button page scrolls faster and faster. how to solve my logical mistake?
function scroll() {
var scrollspeed = document.getElementById("scrollspeedval").value;
if (scrollspeed == 1) {
window.scrollBy(0, 1);
} else if (scrollspeed == 2) {
window.scrollBy(0, 2);
} else if (scrollspeed == 3) {
window.scrollBy(0, 4);
} else if (scrollspeed == 4) {
window.scrollBy(0, 8);
} else if (scrollspeed == 5) {
window.scrollBy(0, 12);
} else if (scrollspeed == 0) {
};
}
$("document").ready(function() {
$(".scrollcl").click(function() {
var interval_for_autoscroll = setInterval(function() {
scroll();
}, 400);
});
});
You should stop the already running interval timer using clearInterval before starting the new one:
clearInterval(interval_for_autoscroll); // where interval_for_autoscroll is declared outside the scope of the callback.
Something like this:
function scroll() {
var $object = $('.object'),
angle = $object.data('angle') || 0;
$object
.css({ 'transform': 'rotateZ(' + angle + 'deg)' })
.data('angle', (angle + 10) % 360);
}
$("document").ready(function() {
var interval_for_autoscroll;
$('.slow').click(function() {
clearInterval(interval_for_autoscroll);
interval_for_autoscroll = setInterval(scroll.bind(window), 400);
});
$('.normal').click(function() {
clearInterval(interval_for_autoscroll);
interval_for_autoscroll = setInterval(scroll.bind(window), 100);
});
$('.fast').click(function() {
clearInterval(interval_for_autoscroll);
interval_for_autoscroll = setInterval(scroll.bind(window), 10);
});
});
.object {
display: inline-block;
width: 100px;
height: 50px;
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="object">
</div>
<button class="slow">slow</button>
<button class="normal">normal</button>
<button class="fast">fast</button>
Seeing as you're using JQuery, I suppose .one() might be a better option for you, if you only want the event to trigger once.
You could try something like this:
$(".scrollcl").one("click",function(){});

How to make fadeOut effect with pure JavaScript

I'm trying to make fade out effect for a div with pure JavaScript.
This is what I'm currently using:
//Imagine I want to fadeOut an element with id = "target"
function fadeOutEffect()
{
var fadeTarget = document.getElementById("target");
var fadeEffect = setInterval(function() {
if (fadeTarget.style.opacity < 0.1)
{
clearInterval(fadeEffect);
}
else
{
fadeTarget.style.opacity -= 0.1;
}
}, 200);
}
The div should fade out smoothly, but it immediately disappears.
What's wrong? How can I solve it?
jsbin
Initially when there's no opacity set, the value will be an empty string, which will cause your arithmetic to fail. That is, "" < 0.1 == true and your code goes into the clearInterval branch.
You can default it to 1 and it will work.
function fadeOutEffect() {
var fadeTarget = document.getElementById("target");
var fadeEffect = setInterval(function () {
if (!fadeTarget.style.opacity) {
fadeTarget.style.opacity = 1;
}
if (fadeTarget.style.opacity > 0) {
fadeTarget.style.opacity -= 0.1;
} else {
clearInterval(fadeEffect);
}
}, 200);
}
document.getElementById("target").addEventListener('click', fadeOutEffect);
#target {
height: 100px;
background-color: red;
}
<div id="target">Click to fade</div>
An empty string seems like it's treated as a 0 by JavaScript when doing arithmetic and comparisons (even though in CSS it treats that empty string as full opacity)
> '' < 0.1
> true
> '' > 0.1
> false
> '' - 0.1
> -0.1
Simpler Approach
We can now use CSS transitions to make the fade out happen with a lot less code
const target = document.getElementById("target");
target.addEventListener('click', () => target.style.opacity = '0');
// If you want to remove it from the page after the fadeout
target.addEventListener('transitionend', () => target.remove());
#target {
height: 100px;
background-color: red;
transition: opacity 1s;
}
<p>Some text before<p>
<div id="target">Click to fade</div>
<p>Some text after</p>
Just this morning I found this piece of code at http://vanilla-js.com, it's very simple, compact and fast:
var s = document.getElementById('thing').style;
s.opacity = 1;
(function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();
You can change the speed of the fade changing the second parameter in the setTimeOut function.
var s = document.getElementById('thing').style;
s.opacity = 1;
(function fade(){(s.opacity-=.1)<0?s.display="none":setTimeout(fade,40)})();
#thing {
background: red;
line-height: 40px;
}
<div id="thing">I will fade...</div>
It looks like you can do it another way(I may be wrong).
event.target.style.transition = '0.8s';
event.target.style.opacity = 0;
you can use CSS transition property rather than doing vai timer in javascript. thats more performance oriented compared to what you are doing.
check
http://fvsch.com/code/transition-fade/test5.html#test3
In addition to the accepted answer, we now have WAAPI which basically adds animation API to JavaScript.
For example,
/**
* #returns {Object}
*/
function defaultFadeConfig() {
return {
easing: 'linear',
iterations: 1,
direction: 'normal',
fill: 'forwards',
delay: 0,
endDelay: 0
}
}
/**
* #param {HTMLElement} el
* #param {number} durationInMs
* #param {Object} config
* #returns {Promise}
*/
async function fadeOut(el, durationInMs, config = defaultFadeConfig()) {
return new Promise((resolve, reject) => {
const animation = el.animate([
{ opacity: '1' },
{ opacity: '0', offset: 0.5 },
{ opacity: '0', offset: 1 }
], {duration: durationInMs, ...config});
animation.onfinish = () => resolve();
})
}
/**
* #param {HTMLElement} el
* #param {number} durationInMs
* #param {Object} config
* #returns {Promise}
*/
async function fadeIn(el, durationInMs, config = defaultFadeConfig()) {
return new Promise((resolve) => {
const animation = el.animate([
{ opacity: '0' },
{ opacity: '0.5', offset: 0.5 },
{ opacity: '1', offset: 1 }
], {duration: durationInMs, ...config});
animation.onfinish = () => resolve();
});
}
window.addEventListener('load', async ()=> {
const el = document.getElementById('el1');
for(const ipsum of "Neque porro quisquam est qui dolorem ipsum quia dolor \uD83D\uDE00".split(' ')) {
await fadeOut(el, 1000);
el.innerText = ipsum;
await fadeIn(el, 2000);
}
});
.text-center {
text-align: center;
}
<h1 id="el1" class="text-center">...</h1>
function fadeOutEffect() {
var fadeTarget = document.getElementById("target");
var fadeEffect = setInterval(function () {
if (!fadeTarget.style.opacity) {
fadeTarget.style.opacity = 1;
}
if (fadeTarget.style.opacity > 0) {
fadeTarget.style.opacity -= 0.1;
} else {
clearInterval(fadeEffect);
}
}, 200);
}
document.getElementById("target").addEventListener('click', fadeOutEffect);
#target {
height: 100px;
background-color: red;
}
<div id="target">Click to fade</div>
my solution
function fadeOut(selector, timeInterval, callback = null) {
var fadeTarget = document.querySelector(selector);
let time = timeInterval / 1000;
fadeTarget.style.transition = time + 's';
fadeTarget.style.opacity = 0;
var fadeEffect = setInterval(function() {
if (fadeTarget.style.opacity <= 0)
{
clearInterval(fadeEffect);
if (typeof (callback) === 'function') {
callback();
}
}
}, timeInterval);
}
While most of the solutions in this and other SO threads work, here are my two cents. If you want to rely only on pure JS ONLY then this should do the trick:
function fadeOutEle(el) {
el.style.opacity = 1;
(function fade() {
if ((el.style.opacity -= .009) < 0) {
el.style.display = "none";
} else {
requestAnimationFrame(fade);
}
})();
};
The Key here is the el.style.opacity -= .009 which give a cool fade out effect. Keep it below 1/2 a second (0.009 in this case) so that the effect is visible before the element hides.

Very Simple, Very Smooth, JavaScript Marquee

I'm trying to find a very simple and smooth, lightweight javascript or jquery marquee. I already tried silk marquee or something, but it wouldn't work with the application I was using. So the simpler and shorter, the better - and easier to debug. Does anybody know of a easy to implement javascript replacement for the marquee?
Pastebin
Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript">
var tWidth='300px'; // width (in pixels)
var tHeight='25px'; // height (in pixels)
var tcolour='#ffffcc'; // background colour:
var moStop=true; // pause on mouseover (true or false)
var fontfamily = 'arial,sans-serif'; // font for content
var tSpeed=3; // scroll speed (1 = slow, 5 = fast)
// enter your ticker content here (use \/ and \' in place of / and ' respectively)
var content='Are you looking for loads of useful information <a href="http:\/\/javascript.about.com\/">About Javascript<\/a>? Well now you\'ve found it.';
var cps=-tSpeed; var aw, mq; var fsz = parseInt(tHeight) - 4; function startticker(){if (document.getElementById) {var tick = '<div style="position:relative;width:'+tWidth+';height:'+tHeight+';overflow:hidden;background-color:'+tcolour+'"'; if (moStop) tick += ' onmouseover="cps=0" onmouseout="cps=-tSpeed"'; tick +='><div id="mq" style="position:absolute;right:0px;top:0px;font-family:'+fontfamily+';font-size:'+fsz+'px;white-space:nowrap;"><\/div><\/div>'; document.getElementById('ticker').innerHTML = tick; mq = document.getElementById("mq"); mq.style.right=(10+parseInt(tWidth))+"px"; mq.innerHTML='<span id="tx">'+content+'<\/span>'; aw = document.getElementById("tx").offsetWidth; lefttime=setInterval("scrollticker()",50);}} function scrollticker(){mq.style.right = (parseInt(mq.style.right)>(-10 - aw)) ?
mq.style.right = parseInt(mq.style.right)+cps+"px": parseInt(tWidth)+10+"px";} window.onload=startticker;
</script>
</head>
<body>
<div id="ticker">
this is a simple scrolling text!
</div>
</body>
</html>
hiya simple demo from recommendations in above comments: http://jsfiddle.net/FWWEn/
with pause functionality on mouseover: http://jsfiddle.net/zrW5q/
hope this helps, have a nice one, cheers!
html
<h1>Hello World!</h1>
<h2>I'll marquee twice</h2>
<h3>I go fast!</h3>
<h4>Left to right</h4>
<h5>I'll defer that question</h5>​
Jquery code
(function($) {
$.fn.textWidth = function(){
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent' : that.css('text-indent'),
'overflow' : that.css('overflow'),
'white-space' : that.css('white-space')
},
marqueeCss = {
'text-indent' : width,
'overflow' : 'hidden',
'white-space' : 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false }, args),
i = 0,
stop = textWidth*-1,
dfd = $.Deferred();
function go() {
if(!that.length) return dfd.reject();
if(width == stop) {
i++;
if(i == args.count) {
that.css(css);
return dfd.resolve();
}
if(args.leftToRight) {
width = textWidth*-1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if(args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if(args.leftToRight) {
width = textWidth*-1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
})(jQuery);
$('h1').marquee();
$('h2').marquee({ count: 2 });
$('h3').marquee({ speed: 5 });
$('h4').marquee({ leftToRight: true });
$('h5').marquee({ count: 1, speed: 2 }).done(function() { $('h5').css('color', '#f00'); })​
I've made very simple function for marquee. See: http://jsfiddle.net/vivekw/pHNpk/2/
It pauses on mouseover & resumes on mouseleave. Speed can be varied. Easy to understand.
function marquee(a, b) {
var width = b.width();
var start_pos = a.width();
var end_pos = -width;
function scroll() {
if (b.position().left <= -width) {
b.css('left', start_pos);
scroll();
}
else {
time = (parseInt(b.position().left, 10) - end_pos) *
(10000 / (start_pos - end_pos)); // Increase or decrease speed by changing value 10000
b.animate({
'left': -width
}, time, 'linear', function() {
scroll();
});
}
}
b.css({
'width': width,
'left': start_pos
});
scroll(a, b);
b.mouseenter(function() { // Remove these lines
b.stop(); //
b.clearQueue(); // if you don't want
}); //
b.mouseleave(function() { // marquee to pause
scroll(a, b); //
}); // on mouse over
}
$(document).ready(function() {
marquee($('#display'), $('#text')); //Enter name of container element & marquee element
});
I just created a simple jQuery plugin for that. Try it ;)
https://github.com/aamirafridi/jQuery.Marquee
The following works:
http://jsfiddle.net/xAGRJ/4/
The problem with your original code was you are calling scrollticker() by passing a string to setInterval, where you should just pass the function name and treat it as a variable:
lefttime = setInterval(scrollticker, 50);
instead of
lefttime = setInterval("scrollticker()", 50);
Why write custom jQuery code for Marquee... just use a plugin for jQuery - marquee() and use it like in the example below:
First include :
<script type='text/javascript' src='//cdn.jsdelivr.net/jquery.marquee/1.3.1/jquery.marquee.min.js'></script>
and then:
//proporcional speed counter (for responsive/fluid use)
var widths = $('.marquee').width()
var duration = widths * 7;
$('.marquee').marquee({
//speed in milliseconds of the marquee
duration: duration, // for responsive/fluid use
//duration: 8000, // for fixed container
//gap in pixels between the tickers
gap: $('.marquee').width(),
//time in milliseconds before the marquee will start animating
delayBeforeStart: 0,
//'left' or 'right'
direction: 'left',
//true or false - should the marquee be duplicated to show an effect of continues flow
duplicated: true
});
If you can make it simpler and better I dare you all people :). Don't make your life more difficult than it should be. More about this plugin and its functionalities at: http://aamirafridi.com/jquery/jquery-marquee-plugin
I made my own version, based in the code presented above by #Tats_innit .
The difference is the pause function. Works a little better in that aspect.
(function ($) {
var timeVar, width=0;
$.fn.textWidth = function () {
var calc = '<span style="display:none">' + $(this).text() + '</span>';
$('body').append(calc);
var width = $('body').find('span:last').width();
$('body').find('span:last').remove();
return width;
};
$.fn.marquee = function (args) {
var that = $(this);
if (width == 0) { width = that.width(); };
var textWidth = that.textWidth(), offset = that.width(), i = 0, stop = textWidth * -1, dfd = $.Deferred(),
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, { count: -1, speed: 1e1, leftToRight: false, pause: false }, args);
function go() {
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i <= args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width=width-2;
}
if (args.pause == false) { timeVar = setTimeout(function () { go() }, args.speed); };
if (args.pause == true) { clearTimeout(timeVar); };
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
timeVar = setTimeout(function () { go() }, 100);
return dfd.promise();
};
})(jQuery);
usage:
for start: $('#Text1').marquee()
pause: $('#Text1').marquee({ pause: true })
resume: $('#Text1').marquee({ pause: false })
My text marquee for more text,
and position absolute enabled
http://jsfiddle.net/zrW5q/2075/
(function($) {
$.fn.textWidth = function() {
var calc = document.createElement('span');
$(calc).text($(this).text());
$(calc).css({
position: 'absolute',
visibility: 'hidden',
height: 'auto',
width: 'auto',
'white-space': 'nowrap'
});
$('body').append(calc);
var width = $(calc).width();
$(calc).remove();
return width;
};
$.fn.marquee = function(args) {
var that = $(this);
var textWidth = that.textWidth(),
offset = that.width(),
width = offset,
css = {
'text-indent': that.css('text-indent'),
'overflow': that.css('overflow'),
'white-space': that.css('white-space')
},
marqueeCss = {
'text-indent': width,
'overflow': 'hidden',
'white-space': 'nowrap'
},
args = $.extend(true, {
count: -1,
speed: 1e1,
leftToRight: false
}, args),
i = 0,
stop = textWidth * -1,
dfd = $.Deferred();
function go() {
if (that.css('overflow') != "hidden") {
that.css('text-indent', width + 'px');
return false;
}
if (!that.length) return dfd.reject();
if (width <= stop) {
i++;
if (i == args.count) {
that.css(css);
return dfd.resolve();
}
if (args.leftToRight) {
width = textWidth * -1;
} else {
width = offset;
}
}
that.css('text-indent', width + 'px');
if (args.leftToRight) {
width++;
} else {
width--;
}
setTimeout(go, args.speed);
};
if (args.leftToRight) {
width = textWidth * -1;
width++;
stop = offset;
} else {
width--;
}
that.css(marqueeCss);
go();
return dfd.promise();
};
// $('h1').marquee();
$("h1").marquee();
$("h1").mouseover(function () {
$(this).removeAttr("style");
}).mouseout(function () {
$(this).marquee();
});
})(jQuery);
Responsive resist jQuery marquee simple plugin. Tutorial:
// start plugin
(function($){
$.fn.marque = function(options, callback){
// check callback
if(typeof callback == 'function'){
callback.call(this);
} else{
console.log("second argument (callback) is not a function");
// throw "callback must be a function"; //only if callback for some reason is required
// return this; //only if callback for some reason is required
}
//set and overwrite default functions
var defOptions = $.extend({
speedPixelsInOneSecound: 150, //speed will behave same for different screen where duration will be different for each size of the screen
select: $('.message div'),
clickSelect: '', // selector that on click will redirect user ... (optional)
clickUrl: '' //... to this url. (optional)
}, options);
//Run marque plugin
var windowWidth = $(window).width();
var textWidth = defOptions.select.outerWidth();
var duration = (windowWidth + textWidth) * 1000 / defOptions.speedPixelsInOneSecound;
var startingPosition = (windowWidth + textWidth);
var curentPosition = (windowWidth + textWidth);
var speedProportionToLocation = curentPosition / startingPosition;
defOptions.select.css({'right': -(textWidth)});
defOptions.select.show();
var animation;
function marquee(animation){
curentPosition = (windowWidth + defOptions.select.outerWidth());
speedProportionToLocation = curentPosition / startingPosition;
animation = defOptions.select.animate({'right': windowWidth+'px'}, duration * speedProportionToLocation, "linear", function(){
defOptions.select.css({'right': -(textWidth)});
});
}
var play = setInterval(marquee, 200);
//add onclick behaviour
if(defOptions.clickSelect != '' && defOptions.clickUrl != ''){
defOptions.clickSelect.click(function(){
window.location.href = defOptions.clickUrl;
});
}
return this;
};
}(jQuery));
// end plugin
Use this custom jQuery plugin as bellow:
//use example
$(window).marque({
speedPixelsInOneSecound: 150, // spped pixels/secound
select: $('.message div'), // select an object on which you want to apply marquee effects.
clickSelect: $('.message'), // select clicable object (optional)
clickUrl: 'services.php' // define redirection url (optional)
});
Marquee using CSS animations.
`<style>
.items-holder {
animation: moveSlideshow 5s linear infinite;
}
.items-holder:hover {
animation-play-state: paused;
}
#keyframes moveSlideshow {
100% {
transform: translateX(100%);
}
}
</style>`
I try use only css for it this link.
<style>
.header {
background: #212121;
overflow: hidden;
height: 65px;
position: relative;
}
.header div {
display: flex;
flex-direction: row;
align-items: center;
overflow: hidden;
height: 65px;
transform: translate(100%, 0);
}
.header div * {
font-family: "Roboto", sans-serif;
color: #fff339;
text-transform: uppercase;
text-decoration: none;
}
.header div img {
height: 60px;
margin-right: 20px;
}
.header .ticker-wrapper__container{
display: flex;
flex-direction: row;
align-items: center;
position: absolute;
top: 0;
right: 0;
animation: ticker 30s infinite linear forwards;
}
.header:hover .ticker-wrapper__container{
animation-play-state: paused;
}
.ticker-wrapper__container a{
display: flex;
margin-right: 60px;
align-items: center;
}
#keyframes ticker {
0% {
transform: translate(100%, 0);
}
50% {
transform: translate(0, 0);
}
100% {
transform: translate(-100%, 0);
}
}
</style>

Categories

Resources