Count Up effect ; 2 plugins interfering - javascript

Trying to develop my website and got a problem with a jQuery plugin.
After searching through google 'till the page 9 of the the search, I've found an working JavaScript plugin that simply counts up ( I'll let a link as an exemple, it's as you scroll down a site and it displays a count up effect from 0 to a desired number in a desired amount of time).
It works amazing - and not gonna lie, it's the the only functional one I found in 8 pages of internet- but, if i try to copy+paste the plugin on the site( like, to double it) it blows the first plugin and they interfere with each other ( no matter what number i set the second one to count till, it will count as the first one). Basically, they blow each other up.
Link: https://jsfiddle.net/YWn9t/
My question:
Why is this thing happening? My hand-errors or?
As far as my experience with coding takes me, i know each plugin has some kind of name, like to indentify which is which. May this be the base of the error? Like, i have to change the name of the second? And if yes, which line/ lines should i modify?
Do you have this kind of plugin?
L.E.: Forgot to mention. I use a sitebuilder: WebWave so it must have a css code, html and jv code.
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
$('.timer').countTo({
from: 50,
to: 2500,
speed: 5000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
.timer {
width: 200px;
margin: 20px auto;
text-align: center;
display: block;
font-size: 20px
}
#help {
width: 500px;
margin: 20px auto;
text-align: center;
display: block;
font-size: 14px
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="timer"></span>
<hr/>
<span id="help">From: 50 - To: 2500 / Over 5000 Milli-Seconds</span>

Works for me when I use unique IDs
Remove the display:block to align horizontally
For example
(function($) {
$.fn.countTo = function(options) {
options = $.extend({}, $.fn.countTo.defaults, options || {});
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0,
to: 100,
speed: 1000,
refreshInterval: 100,
decimals: 0,
onUpdate: null,
onComplete: null,
};
})(jQuery);
jQuery(function($) {
$('#timer1').countTo({
from: 50,
to: 2500,
speed: 5000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
$('#timer2').countTo({
from: 1550,
to: 4500,
speed: 5000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
.timer {
width: 200px;
margin: 20px auto;
text-align: center;
font-size: 20px;
padding: 50px;
}
#help {
width: 500px;
margin: 20px auto;
text-align: center;
display: block;
font-size: 14px
}
#container {
text-align: center
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<span class="timer" id="timer1"></span>
<span class="timer" id="timer2"></span>
</div>
<hr/>
<span id="help">From: 50 - To: 2500 / Over 5000 Milli-Seconds</span>

Related

Add Prev Next Controls to Carousel

After toying about with timers and intervals I have come to a solution that works to my satisfaction.
See relevant jsFiddle or code below:
HTML:
<div id="foo">irrelevant content</div>
javascript( with jQuery):
var post_array = [ "abc", "123", "xyz" ];
var class_array = [ "red", "blue", "green" ];
var interval = 2000;
var i = 0;
var max = post_array.length;
var id ="#foo";
$(id).html(post_array[0]);
$(id).removeClass().addClass(class_array[0]);
setInterval( function(){
++i;
$(id).fadeOut("slow", function() {
$(id).html(post_array[i%max]).fadeIn("slow");
$(id).removeClass().addClass(class_array[i%max]);
});
}, interval);
Now I wonder what the best way to add two side arrows that allow me to go back and fort would be.
should I have written the relevant code in a named function so I can call it and pass an index parameter when the button is pressed? ( how do i act on the same index variable in that case? )
What's the best practice for button overlays?
Help!
Thanks in advance
Carousels should be modular, reusable and extendable. Don't copy paste JS code when in need to add another Carousel into your DOM.
In order to create PREV / NEXT buttons you'll also need a method to stop your interval: stop
When you hover over your Carousel, you'll need to pause the autoplay to prevent a really bad User Experience (UX)
Don't animate using jQuery. Animate by simply assigning an is-active class to the current index slide, and use CSS to do whatever you want with that class.
Use a variable index (start with 0) to keep track of the current slide index
You Might Not Need jQuery
Aim to create a class instance using the sugary class or the proper prototype syntax - that can be used like:
const myCarousel = new Carousel({
target: "#carousel-one",
slides: [
{
title: "This is slide one",
image: "images/one.jpg"
},
{
title: "This is slide two! Yey.",
image: "images/two.jpg"
}
]
});
So basically, you'll need a constructor that has those methods:
Method
Description
anim()
Fix index if exceeds slides or is negative and animate to new index
prev()
Decrement index and trigger anim()
next()
Increment index and trigger anim()
stop()
Clear loop interval (On mouseenter)
play()
Start loop (Triggers next() every pause milliseconds)
Simple JavaScript carousel example
class Carousel {
constructor(options) {
Object.assign(this, {
slides: [],
index: 0,
pause: 4000, // Pause between slides
EL: document.querySelector(options.target || "#Carousel"),
autoplay: true,
}, options);
this.total = this.slides.length;
this.EL_area = this.EL.querySelector(".Carousel-area");
this.EL_prev = this.EL.querySelector(".Carousel-prev");
this.EL_next = this.EL.querySelector(".Carousel-next");
const NewEL = (tag, prop) => Object.assign(document.createElement(tag), prop);
// Preload images
this.ELs_items = this.slides.reduce((DF, item) => {
const EL_slide = NewEL("div", {
className: "Carousel-slide"
});
const EL_image = NewEL("img", {
className: "Carousel-image",
src: item.image,
alt: item.title
});
const EL_content = NewEL("div", {
className: "Carousel-title",
textContent: item.title
});
EL_slide.append(EL_image, EL_content);
DF.push(EL_slide);
return DF;
}, []);
this.EL_area.append(...this.ELs_items);
// Events
this.EL_prev.addEventListener("click", () => this.prev());
this.EL_next.addEventListener("click", () => this.next());
this.EL.addEventListener("mouseenter", () => this.stop());
this.EL.addEventListener("mouseleave", () => this.play());
// Init
this.anim();
this.play();
}
// Methods:
anim() {
this.index = this.index < 0 ? this.total - 1 : this.index >= this.total ? 0 : this.index;
this.ELs_items.forEach((EL, i) => EL.classList.toggle("is-active", i === this.index));
}
prev() {
this.index -= 1;
this.anim();
}
next() {
this.index += 1;
this.anim();
}
stop() {
clearInterval(this.itv);
}
play() {
if (this.autoplay) this.itv = setInterval(() => this.next(), this.pause);
}
}
// Use like:
new Carousel({
target: "#carousel-one",
slides: [{
title: "We're part of nature",
image: "https://picsum.photos/id/10/400/300"
},
{
title: "Remember to read and learn",
image: "https://picsum.photos/id/24/400/300"
},
{
title: "Up for a coffee?",
image: "https://picsum.photos/id/30/400/300"
},
]
});
/* CAROUSEL */
.Carousel {
position: relative;
height: 300px;
max-height: 100vh;
}
.Carousel-slide {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
transition: opacity 0.5s; /* DESIRED SLIDE TRANSITIONS */
opacity: 0; /* INACTIVE SLIDE*/
}
.Carousel-slide.is-active { /* ACTIVE SLIDE! */
opacity: 1;
z-index: 1;
}
.Carousel-prev,
.Carousel-next {
position: absolute;
z-index: 2;
top: 50%;
transform: translateY(-50%);
user-select: none; /* Prevent highlight */
}
.Carousel-prev {
left: 1em;
}
.Carousel-next{
right: 1em;
}
.Carousel-image {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover;
}
.Carousel-title {
position: absolute;
width: 100%;
height: 100%;
color: #fff;
display: flex;
justify-content: center;
align-items: center;
font-size: 3em;
}
<div class="Carousel" id="carousel-one">
<div class="Carousel-area"></div>
<button class="Carousel-prev" type="button" aria-label="Previous slide">←</button>
<button class="Carousel-next" type="button" aria-label="Next slide">→</button>
<div class="Carousel-desc"></div>
</div>
With the above code you can have an unlimited number of carousels on a single page given every one has a different target ID.
PS: Alternatively, if your code keeps track of the direction for the prev / next, the logic to increment/decrement/loopback the current index can be also written as (pseudocode ahead!):
C = (is_next ? ++C : --C) < 0 ? T-1 : C%T;
where C is the current index, T is the total number of slides, and is_next is a boolean that is true when the direction is Next.

Dynamically change animation speed

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

how to execute code when arriving to a specific div

I've looked at some similar questions, but couldn't find a solution that worked for me. I have some counters on my page, and I want them to start counting only when I reach that div in my view. any ideas? Thanks.
Here's my code...:
// JS plugin + code for counter up
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
var div_header = $('#counters').offset().top;
var window_top = $(window).scrollTop();
//alert(window_top);
//alert(div_header);
if(div_header == window_top) {
alert('success');
}
$('.hours span').countTo({
from: 50,
to: 1400,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
$('.exposure span.numbers').countTo({
from: 50,
to: 300,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
$('.types span').countTo({
from: 0,
to: 10,
speed: 2000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
#counters {
font-family: 'opensans', sans-serif;
color: white;
font-size: 5em;
display: block;
padding: 4%;
text-align: center;
font-weight: 100;
background-color: #222020;
}
#counters div {
width: 30%;
display: inline-block;
vertical-align: top;
}
#counters span, .exposure:after {
font-size: 0.8em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<section id="counters">
<div class="hours">
<span></span>
<h3>header1</h3>
</div>
<div class="exposure">
<span class="numbers"></span><span>%</span>
<h3>header2</h3>
</div>
<div class="types">
<span></span>
<h3>header3</h3>
</div>
</section>

Bar chart plugin - IE9-110 issue with chart expanding outside of container

I've made a simple bar chart plugin which takes some settings and data and displays it as a percentage, it's working perfectly fine in all browsers except IE9-10.
The chart still displays fine yet there is a weird 'jump' once each of the bars have finished animating where the table seems to gain additional height. I've measured the height of the bars in the chart in browsers where it's working fine and there appears to be an additional ~50px height being added in browsers where the weird 'jump' effect occurs.
Here is the relevant CSS:
#barchart {
text-align: center;
}
.bar {
margin-right: 10px;
position: relative;
bottom: 0;
overflow: hidden;
padding-top: 50px;
height: 100%;
}
.bar .label {
text-align: center;
width: inherit;
margin: 0 auto 20px auto;
width: 116px;
}
.bar__value {
height: 0%;
background-repeat: repeat-y;
background-position: top center;
margin: 0 5px;
}
And here is the JS:
var Crafted = (function(c) {
return c;
})(Crafted || {});
(function($, c) {
c.BarChart = (function() {
var barChart = function(target, options, data) {
this.target = target;
this.ChartItem(options);
this.data = data;
this.create();
};
barChart.prototype.ChartItem = function(options) {
var settings = $.extend({
width: '100%',
height: '500px',
usePercentSymbol: false,
delay: 1000,
animSpeed: 1000,
chartImage: '',
chartBgColour: '#CCCCCC'
}, options);
this.width = settings.width;
this.height = settings.height;
this.usePercentSymbol = settings.usePercentSymbol;
this.delay = settings.delay;
this.animSpeed = settings.animSpeed;
this.chartImage = settings.chartImage;
this.chartBgColour = settings.chartBgColour;
return this;
};
barChart.prototype.create = function() {
var _self = this;
if (!_self.target) {
console.error('Error: BarChart \'target\' must be specified');
return;
}
if (!_self.data) {
console.error('Error: BarChart \'data\' must be provided');
return;
}
var $barChart = $('<table></table>').attr('id', 'barchart');
var $charts = $('<tr></tr>').addClass('data-row');
$charts.appendTo($barChart);
$barChart.appendTo(_self.target);
$barChart.attr('width', _self.width)
.attr('height', _self.height);
$.each(_self.data, function(index, value) {
var $chart = $('<td></td>')
.addClass('bar')
.attr('valign', 'bottom')
.attr('data-percent', value.percent);
$chart.appendTo($charts);
var $chartLabel = $('<div></div>').addClass('label');
$chartLabel.appendTo($chart);
var $chartValue = $('<div></div>').addClass('label__percent').text(_self.usePercentSymbol ? '0%' : 0);
$chartValue.appendTo($chartLabel);
var $chartTitle = $('<div></div>').addClass('label__title').text(value.label);
$chartTitle.appendTo($chartLabel);
var $barValue = $('<div></div>').addClass('bar__value');
var barStyle = _self.chartImage ?
'background-image:url(\'' + _self.chartImage + '\');' :
'background-color:' + _self.chartBgColour
$barValue.attr('style', barStyle);
$barValue.appendTo($chart);
});
setTimeout(function() {
$('.bar').each(function() {
var percentage = $(this).attr('data-percent');
var $percentLbl = $(this).find('.label__percent');
$(this).children('.bar__value').animate({
height: percentage + '%'
}, _self.animSpeed);
$({
countNum: 0
}).animate({
countNum: percentage
}, {
duration: _self.animSpeed,
easing: 'linear',
progress: function() {
var currentValue = Math.floor(this.countNum);
$percentLbl.text(_self.usePercentSymbol ? currentValue + '%' : currentValue);
}
});
});
}, _self.delay);
};
return barChart;
})();
})(jQuery, Crafted);
$(function() {
(function(c) {
var settings = {
width: '800px',
height: '400px',
usePercentSymbol: true,
delay: 200,
animSpeed: 1000,
chartImage: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/662693/chimney.svg'
};
var data = [{
label: 'MANCHESTER',
percent: 78
}, {
label: 'BIRMINGHAM',
percent: 69
}, {
label: 'LONDON',
percent: 94
}, {
label: 'CARDIFF',
percent: 39
}, {
label: 'GLASGOW',
percent: 54
}, {
label: 'BELFAST',
percent: 35
}]
var barChart = new c.BarChart('#barChart', settings, data);
})(Crafted);
});
I have a JsFiddle that demonstrates the problem. If you load this in IE9/10 (you can use the browser emulator in IE dev tools - F12) you will see the strange effect I'm talking about. This doesn't occur in IE11/Edge etc...
Could it be due to the padding top applied to the <td> elements? This is used to give enough spacing for each chart label to prevent them from being cut off.
try with this css modification to bar class
.bar {
margin-right: 10px;
position: relative;
bottom: 0;
overflow: hidden;
padding-top: 50px;
height: 75%;
}
seems it works either on ie9/10 and chrome

Make words pulsate and change of place randomly

I'm doing this plugin that takes the words and makes them pulsate on the screen:
First they appear and grow, then they vanish, change place and again appear
Working plugin:
+ function($) {
var Pulsate = function(element) {
var self = this;
self.element = element;
self.max = 70;
self.min = 0;
self.speed = 500;
self.first = true;
self.currentPlace;
self.possiblePlaces = [
{
id: 0,
top: 150,
left: 150,
},
{
id: 1,
top: 250,
left: 250,
},
{
id: 2,
top: 350,
left: 350,
},
{
id: 3,
top: 250,
left: 750,
},
{
id: 4,
top: 450,
left: 950,
}
];
};
Pulsate.prototype.defineRandomPlace = function() {
var self = this;
self.currentPlace = self.possiblePlaces[Math.floor(Math.random() * self.possiblePlaces.length)];
if(!self.possiblePlaces) self.defineRandomPlace;
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
};
Pulsate.prototype.animateToZero = function() {
var self = this;
self.element.animate({
'fontSize': 0,
'queue': true
}, self.speed, function() {
self.defineRandomPlace();
});
};
Pulsate.prototype.animateToRandomNumber = function() {
var self = this;
self.element.animate({
'fontSize': Math.floor(Math.random() * (70 - 50 + 1) + 50),
'queue': true
}, self.speed, function() {
self.first = false;
self.start();
});
};
Pulsate.prototype.start = function() {
var self = this;
if (self.first) self.defineRandomPlace();
if (!self.first) self.animateToZero();
self.animateToRandomNumber();
};
$(window).on('load', function() {
$('[data-pulsate]').each(function() {
var element = $(this).data('pulsate') || false;
if (element) {
element = new Pulsate($(this));
element.start();
}
});
});
}(jQuery);
body {
background: black;
color: white;
}
.word {
position: absolute;
text-shadow: 0 0 5px rgba(255, 255, 255, 0.9);
font-size: 0px;
}
.two {
position: absolute;
color: white;
left: 50px;
top: 50px;
}
div {
margin-left: 0px;
}
<span class="word" data-pulsate="true">Love</span>
<span class="word" data-pulsate="true">Enjoy</span>
<span class="word" data-pulsate="true">Huggs</span>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
If you notice i define the places that the word can grow in the self.possiblePlaces, and if you notice the animation, sometimes more then one word can grow in one place, my goal coming here is ask for help. How I can make two words never grow in the same place??
I was trying to do like this:
In the defineRandomPlace i pick a random object inside my possiblePlaces array:
Pulsate.prototype.defineRandomPlace = function() {
var self = this;
self.currentPlace = self.possiblePlaces[Math.floor(Math.random() * self.possiblePlaces.length)];
if(!self.possiblePlaces) self.defineRandomPlace;
delete self.possiblePlaces[self.currentPlace.id];
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
};
Notice the delete, first i clone the chosen object, after I delete it but keep his place in the array.
After the animation was over, I put the object in the array again, before starting all over again:
Pulsate.prototype.animateToZero = function() {
var self = this;
self.element.animate({
'fontSize': 0,
'queue': true
}, self.speed, function() {
self.possiblePlaces[self.currentPlace.id] = self.currentPlace;
self.defineRandomPlace();
});
But it made no difference.
Thanks!!
Pen: http://codepen.io/anon/pen/waooQB
In your example, you are randomly picking from a list that has five members, and you have three separate words that could be displayed, putting chance of overlap fairly high.
A simple approach to resolve is to pick the first item in the list, remove it from the list, and the append to the end of the list each time. Because you have more positions in the lists than items selecting from it, you're guaranteed to never collide.
Share the same list possiblePlaces between all instances.
Shift the first item off the queue, and push it onto the end when its done each time, instead of selecting randomly in defineRandomPlace.
Snippet highlighting #2:
// shift a position off the front
self.currentPlace = possiblePlaces.shift();
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
// push it back on the end
possiblePlaces.push(self.currentPlace);
If you want it truly random, you'll need to randomly select and remove an item from the array, and not put it back into the array until after it's been used. You'll also need to always ensure that you have more possiblePlaces than you have dom elements to place on the page.
Like so:
Pulsate.prototype.defineRandomPlace = function() {
var self = this;
var newPlace = possiblePlaces.splice(Math.floor(Math.random()*possiblePlaces.length), 1)[0];
if (self.currentPlace) {
possiblePlaces.push(self.currentPlace);
}
self.currentPlace = newPlace;
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
};
See http://codepen.io/anon/pen/bdBBPE
My decision is to divide the page to imaginary rows and to prohibit more than one word in the same row. Please check this out.
Note: as the code currently does not support recalculating of rows count on document resize, the full page view will not display correctly. Click "reload frame" or try JSFiddle or smth.
var pulsar = {
// Delay between words appearance
delay: 400,
// Word animation do not really depend on pulsar.delay,
// but if you set pulsar.delay small and wordAnimationDuration long
// some words will skip their turns. Try 1, 2, 3...
wordAnimationDuration: 400 * 3,
// Depending on maximum font size of words we calculate the number of rows
// to which the window can be divided
maxFontSize: 40,
start: function () {
this.computeRows();
this.fillWords();
this.animate();
},
// Calculate the height or row and store each row's properties in pulsar.rows
computeRows: function () {
var height = document.body.parentNode.clientHeight;
var rowsCount = Math.floor(height/this.maxFontSize);
this.rows = [];
for (var i = 0; i < rowsCount; i++) {
this.rows.push({
index: i,
isBusy: false
});
}
},
// Store Word instances in pulsar.words
fillWords: function () {
this.words = [];
var words = document.querySelectorAll('[data-pulsate="true"]');
for (var i = 0; i < words.length; i++) {
this.words.push(new Word(words[i], this.wordAnimationDuration, this.maxFontSize));
}
},
// When it comes time to animate another word we need to know which row to move it in
// this random row should be empty at the moment
getAnyEmptyRowIndex: function () {
var emptyRows = this.rows.filter(function(row) {
return !row.isBusy;
});
if (emptyRows.length == 0) {
return -1;
}
var index = emptyRows[Math.floor(Math.random() * emptyRows.length)].index;
this.rows[index].isBusy = true;
return index;
},
// Here we manipulate words in order of pulsar.words array
animate: function () {
var self = this;
this.interval = setInterval(function() {
var ri = self.getAnyEmptyRowIndex();
if (ri >= 0) {
self.words.push(self.words.shift());
self.words[0].animate(ri, function () {
self.rows[ri].isBusy = false;
});
}
}, this.delay);
}
}
function Word (span, duration, maxFontSize) {
this.span = span;
this.inAction = false;
this.duration = duration;
this.maxFontSize = maxFontSize;
}
/**
* #row {Numer} is a number of imaginary row to place the word into
* #callback {Function} to call on animation end
*/
Word.prototype.animate = function (row, callback) {
var self = this;
// Skip turn if the word is still busy in previous animation
if (self.inAction) {
return;
}
var start = null,
dur = self.duration,
mfs = self.maxFontSize,
top = row * mfs,
// Random left offset (in %)
left = Math.floor(Math.random() * 90),
// Vary then font size within half-max size and max size
fs = mfs - Math.floor(Math.random() * mfs / 2);
self.inAction = true;
self.span.style.top = top + 'px';
self.span.style.left = left + '%';
function step (timestamp) {
if (!start) start = timestamp;
var progress = timestamp - start;
// Calculate the factor that will change from 0 to 1, then from 1 to 0 during the animation process
var factor = 1 - Math.sqrt(Math.pow(2 * Math.min(progress, dur) / dur - 1, 2));
self.span.style.fontSize = fs * factor + 'px';
if (progress < dur) {
window.requestAnimationFrame(step);
}
else {
self.inAction = false;
callback();
}
}
window.requestAnimationFrame(step);
}
pulsar.start();
body {
background: black;
color: white;
}
.word {
position: absolute;
text-shadow: 0 0 5px rgba(255, 255, 255, 0.9);
font-size: 0px;
/* To make height of the .word to equal it's font size */
line-height: 1;
}
<span class="word" data-pulsate="true">Love</span>
<span class="word" data-pulsate="true">Enjoy</span>
<span class="word" data-pulsate="true">Huggs</span>
<span class="word" data-pulsate="true">Peace</span>
I updated your plugin constructor. Notice the variable Pulsate.possiblePlaces, I have changed the variable declaration this way to be able to share variable data for all Object instance of your plugin.
var Pulsate = function(element) {
var self = this;
self.element = element;
self.max = 70;
self.min = 0;
self.speed = 500;
self.first = true;
self.currentPlace;
Pulsate.possiblePlaces = [
{
id: 0,
top: 150,
left: 150,
},
{
id: 1,
top: 250,
left: 250,
},
{
id: 2,
top: 350,
left: 350,
},
{
id: 3,
top: 250,
left: 750,
},
{
id: 4,
top: 450,
left: 950,
}
];
};
I added occupied attribute to the possible places to identify those that are already occupied. If the randomed currentPlace is already occupied, search for random place again.
Pulsate.prototype.defineRandomPlace = function() {
var self = this;
self.currentPlace = Pulsate.possiblePlaces[Math.floor(Math.random() * Pulsate.possiblePlaces.length)];
if(!Pulsate.possiblePlaces) self.defineRandomPlace;
if (!self.currentPlace.occupied) {
self.currentPlace.occupied = true;
self.element.css('top', self.currentPlace.top + 'px');
self.element.css('left', self.currentPlace.left + 'px');
} else {
self.defineRandomPlace();
}
};
Every time the element is hidden, set the occupied attribute to false.
Pulsate.prototype.animateToZero = function() {
var self = this;
self.element.animate({
'fontSize': 0,
'queue': true
}, self.speed, function() {
self.currentPlace.occupied = false;
self.defineRandomPlace();
});
};
A small hint f = 0.5px x = 100px t = 0.5s
x / f = 200
200/2 * t * 0.5 = f(shrink->expand until 100px square) per 0.5 seconds

Categories

Resources