Blinking divs like traffic lights? - javascript

I have this website: backlinkbeat.com. To the down, there are 3 divs having the background images. Each background-image includes a number like "1", "2", "3". I want those divs to blink as traffic lights respectively.
The script I wrote is not blinking the lights correctly as you can see in the link which means that it is not blinking the correct order. I want to blink them in the way are shown in the markup:
<div style="float:left; height:400px;">
<div style=" margin-top:50px;">
<div class="list cufon one" id="blink1" style="width:420px;">put you on just any, <span style="color:#1fbfd1;">www.yourwebsite.com</span>
</div>
<div class="list cufon two" id="blink2" style="width:420px;">Press <span style="color:#1fbfd1;">"do it"</span>
</div>
<div class="list cufon three" id="blink3" style="width:420px;">see the backlinks <span style="color:#1fbfd1;">roll in!</span>
</div>
</div>
</div>
The script I wrote which donot work correctly is:
setInterval(function () {
setTimeout(function(){
var vis1 = $("#blink1").css("visibility");
vis1 = (!vis1 || vis1 == "visible") ? "hidden" : "visible";
$("#blink1").css("visibility", vis1);
}, 1000);
}, 1000);
setInterval(function() {
setTimeout(function(){
var vis2 = $("#blink2").css("visibility");
vis2 = (!vis2 || vis2 == "visible") ? "hidden" : "visible";
$("#blink2").css("visibility", vis2);
}, 2000);
}, 2000);
setInterval(function() {
setTimeout(function(){
var vis3 = $("#blink3").css("visibility");
vis3 = (!vis3 || vis3 == "visible") ? "hidden" : "visible";
$("#blink3").css("visibility", vis3);
}, 3000);
}, 3000);
Thanks,
Areeb

I suggest you give your elements a common class, ex:
<div class="blink">One</div>
<div class="blink">Two</div>
<div class="blink">Three</div>
Then you can simplify your code to:
//Cache element collection and keep a reference to the visible element
var $elements = $('.blink').css('visibility','hidden'),
$visible = $elements.first().css('visibility','visible');
//Single interval function to handle blinking
setInterval(function(){
//Hide visible element
$visible.css('visibility','hidden');
//Find next one
var $next = $visible.next('.blink');
if(!$next.length)
$next = $elements.first();
//Show next element
$visible = $next.css('visibility','visible');
},1000);
Demo fiddle

This may be what you're looking for. http://jsfiddle.net/andaywells/eQuXn/15/
I have modified this code: http://jsfiddle.net/paislee/pdsu7/5/
So that each div stays in position, the 'hold' div keeps it there.
$(document).ready(function () {
var delay = 5000,
fade = 500;
var banners = $('.banner');
var len = banners.length;
var i = 0;
setTimeout(cycle, delay);
function cycle() {
$(banners[i % len]).fadeOut(fade, function () {
$(banners[++i % len]).fadeIn(fade, function () {
setTimeout(cycle, delay);
});
});
}
});

Perhaps this example will help you.
CSS
.lamp {
height: 30px;
width: 30px;
border-style: solid;
border-width: 2px;
}
.lampRed {
background-color: red;
}
.lampYellow {
background-color: yellow;
}
.lampGreen {
background-color: green;
}
HTML
<div id="trafficLight">
<div>Click to Start and Stop</div>
<div class="lamp" id="Red"></div>
<div class="lamp" id="Yellow"></div>
<div class="lamp" id="Green"></div>
</div>
Javascript
var changeState = (function () {
var state = 0,
lamps = ["Red", "Yellow", "Green"],
lampsLength = lamps.length,
order = [
[5000, "Red"],
[3000, "Red", "Yellow"],
[5000, "Green"],
[3000, "Yellow"]
],
orderLength = order.length,
lampIndex,
orderIndex,
sId;
return function (stop) {
if (stop) {
clearTimeout(sId);
return;
}
var lamp,
lampDOM;
for (lampIndex = 0; lampIndex < lampsLength; lampIndex += 1) {
lamp = lamps[lampIndex];
lampDOM = document.getElementById(lamp);
if (order[state].indexOf(lamp) !== -1) {
lampDOM.classList.add("lamp" + lamp);
} else {
lampDOM.classList.remove("lamp" + lamp);
}
}
sId = setTimeout(changeState, order[state][0]);
state += 1;
if (state >= orderLength) {
state = 0;
}
};
}());
document.getElementById("trafficLight").addEventListener("click", (function () {
var state = false;
return function () {
changeState(state);
state = !state;
};
}()), false);
On jsfiddle

Related

JQuery show a div for 4 seconds, then hide it and show a different one for 1.4 seconds, and finally the first one with some text in a loop

I am working on a project that requires showing a grey screen to show images from an array. How can this be done using javascript?
I have tried using setinterval like so:
document.getElementById("startStimulation").addEventListener("click", startStimulation);
var images = [];
images[0] = 'resources/mentalImg/img/carretera.jpeg';
images[1] = 'resources/mentalImg/img/ciudad.jpg';
images[2] = 'resources/mentalImg/img/ciudad.jpg';
images[3] = 'resources/mentalImg/img/construccion.jpeg';
images[4] = 'resources/mentalImg/img/fabrica.jpg';
images[5] = 'resources/mentalImg/img/terreno.jpg';
function startStimulation() {
var current = 0;
var interval = setInterval(function () {
var firstInnerInterval = setInterval(function () {
$('#text').text('');
$('#flip').hide();
$('#text').show();
}, 4000);
var secondInnerInterval = setInterval(function () {
$('#text').hide();
$('#flip').attr('src', images[current]);
$('#flip').show();
}, 1400);
var thirdInnerInterval = setInterval(function () {
$('#flip').hide();
$('#text').text(someVariable);
$('#text').show();
}, 4000);
if (current < images.length - 1) {
current = current + 1;
} else {
clearInterval(interval);
}
}, 9400);
}
But the output is not the desired. HOw can i achieve this using jQuery?
Is this what you desire?
document.getElementById("startStimulation").addEventListener("click", startStimulation);
var images = [];
images[0] = 'resources/mentalImg/img/carretera.jpeg';
images[1] = 'resources/mentalImg/img/ciudad.jpg';
images[2] = 'resources/mentalImg/img/ciudad.jpg';
images[3] = 'resources/mentalImg/img/construccion.jpeg';
images[4] = 'resources/mentalImg/img/fabrica.jpg';
images[5] = 'resources/mentalImg/img/terreno.jpg';
var current = 0;
var text = $('#text');
var flip = $('#flip');
var both = text.add(flip);
function startStimulation() {
text.text('');
flip.hide();
setTimeout(function() {
both.toggle();
flip.attr('src', images[current]);
}, 4000);
setTimeout(function() {
both.toggle();
text.text("Some randowm text");
}, 5400);
setTimeout(function() {
if (current < images.length - 1) {
current++;
startStimulation();
}
}, 9400)
}
#text {
height: 100px;
width: 100px;
border: 1px solid red;
}
#flip {
height: 100px;
width: 100px;
border: 1px solid #0f0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="text"></div>
<img id="flip">
<button id="startStimulation">Start</button>

How could I make this active onclick?

var span = document.getElementById('loading_dots');
var int = setInterval(function() {
if ((span.innerHTML += '●').length == 4)
span.innerHTML = '';
}, 400);
(function(){
var loading_dots = document.getElementById("loading_dots"),
show = function(){
loading_dots.style.display = "block";
setTimeout(hide, 5000); // 5 seconds
},
hide = function(){
loading_dots.style.display = "none";
};
show();
})();
How can I make it so loading_dots start on the click of a button, and re-activates everytime I click the button? the bottom function is to stop it after 5 seconds, maybe could merge it into one function?
Needs to work for 3 seperate buttons and relaunch on click of each, also needs to display inside of <span class="loading_dots" id="loading_dots"></span> any method is fine, css, jquery, or javascript
here is a jQuery version:
(function ( $ ) {
$.fn.loader = function( options ) {
var settings = $.extend({
text:"●",
spn: undefined
}, options );
$.each(this, function(){
var btn = this;
var int;
var spn;
if (settings.spn === undefined) {
spn = $("<span/>" , { "class":"loading_dots" });
$(btn).append(spn);
} else {
spn= $(settings.spn);
}
var show = function(){
btn.setAttribute("disabled", "disabled")
clearInterval(int);
spn.show();
int = setInterval(function() {
if ((spn[0].innerHTML += settings.text).length == 4)
spn.html("");
}, 400);
setTimeout(hide, 5000); // 5 seconds
}
var hide = function (){
spn.hide();
btn.removeAttribute("disabled", "disabled")
clearInterval(int);
}
btn.addEventListener("click", show);
});
};
}( jQuery ));
// now bind it by its class, this only need to be run once every time new button is added to the html
$(".btn").loader({spn:".loading_dots"});
// and you could also specify the text by
// $(".btn").loader({text: "*"});
.loading_dots {
color:red;
display:none;
width:100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<span class="loading_dots"></span>
<button class="btn" type="button" >
submit
</button>
<button class="btn" type="button" >
submit
</button>
</div>
If you want to add an event listener for a button click, just select the buttons, and add the listeners in a loop:
document.querySelectorAll("button").forEach(e => e.addEventListener("click", myFunc));
Alternatively, listen for any click, then check if the event's target is a button:
document.addEventListener("click", (e) => if (e.target.tagName == "BUTTON") myFunc());
You could use CSS for the most part of your code, and than simply toggle a show class on the parent #loading element:
const Loading = () => {
let tOut = null;
const el = document.querySelector("#loading");
const show = () => {
el.classList.add('show');
tOut = setTimeout(hide, 5000);
};
const hide = () => {
el.classList.remove('show');
clearTimeout(tOut);
};
return {
show,
hide
};
};
const loadingDots = Loading();
const loadBtns = document.querySelectorAll('.load');
[...loadBtns].forEach(el => el.addEventListener('click', loadingDots.show));
// you can always use loadingDots.hide() to hide when needed (before the 5sec ticks out)
#loading {
position: fixed;
z-index: 100;
top:0;
left: 0;
width:100vw;
height:100vh;
display:flex;
background: rgba(0,0,0,0.5);
color: #fff;
font-size: 3em;
align-items: center;
justify-content:center;
visibility: hidden;
opacity: 0;
transition: 0.4s;
}
#loading.show {
opacity: 1;
visibility: visible;
}
#keyframes blink {
50% {opacity: 1;}
}
#loading i:after {content: "\25cf";}
#loading i { opacity: 0; animation: blink 1.2s infinite; }
#loading i:nth-child(2) { animation-delay: .2s; }
#loading i:nth-child(3) { animation-delay: .4s; }
<div id="loading"><i></i><i></i><i></i></div>
<button class="load">LOAD</button>
<button class="load">LOAD</button>
<button class="load">LOAD</button>
A plain javascript version with the option to programmatically/manually stop displaying the loading dots. Just pass the id of the parent element you want the loading to be attached to. By default the loading will be appended to the parent but you can optionally pass an object as the last parameter with a position property.
function removeLoading(id) {
var parent = document.getElementById(id);
var spans = parent.getElementsByClassName("loading_dots");
while (spans.length > 0) {
var span = spans[0];
if (span.dataset.timerId) {
clearTimeout(span.dataset.timerId);
}
span.remove();
}
}
function addLoading(id, options) {
options = options || {};
var parent = document.getElementById(id);
var existingSpans = parent.getElementsByClassName("loading_dots");
if (existingSpans.length > 0) {
removeLoading(id);
}
var span = document.createElement("span");
span.setAttribute("class", "loading_dots");
if (options.timerId) {
span.dataset.timerId = options.timerId;
}
parent.insertAdjacentElement(options.position || "beforeend", span);
setInterval(function () {
if ((span.innerHTML += '●').length == 4)
span.innerHTML = '';
}, 400)
}
function addLoadingWithTimeout(id, ms, options) {
options = options || {};
var timerId = setTimeout(function () { removeLoading(id) }, ms);
options.timerId = timerId;
addLoading(id, options);
}
<p id="load1">Load 1 - Will stop automatically in 3 seconds after starting. </p>
<button onclick="addLoadingWithTimeout('load1', 3000)">Start Load 1</button>
<button onclick="removeLoading('load1')">Stop Load 1</button>
<p id="load2">Load 2 - Only manual Stop </p>
<button onclick="addLoading('load2')">Start Load 2</button>
<button onclick="removeLoading('load2')">Stop Load 2</button>
Here you go. on the HTML side, you just pass the event to the button that you want and then the id, as a string, of the span/div where you want the load icons to appear.
HTML:
<button id="btn" onclick="load(event, 'loadDiv')">Load</button>
<div>
<span id="loadDiv"></span>
</div>
Below, we are getting the btn id from event so you don't have to manually pass it everytime. Then we are defining function for the innerhtml icons. Lastly, we are running the showIcon function every .4s and then clearing the interval after 5 seconds.
JS:
function load(e, location) {
var btn = document.getElementById(e.srcElement.id)
var loadDiv = document.getElementById(location)
function showLoad() {
if (loadDiv.innerHTML.length < 3) {
return loadDiv.innerHTML += '●'
}
loadDiv.innerHTML = ''
}
(function() {
var loadIcons = setInterval(function() {
showLoad()
}, 400)
var clear = setTimeout(function() {
clearInterval(loadIcons)
}, 5000)
})()
}
Hope this helps!
You can define your code in a function and add click handler to the button.
function myFunc() {
var span = document.getElementById('loading_dots');
var int = setInterval(function() {
if ((span.innerHTML += '●').length == 4)
span.innerHTML = '';
}, 400);
(function(){
var loading_dots = document.getElementById("loading_dots"),
show = function(){
loading_dots.style.display = "block";
setTimeout(hide, 5000); // 5 seconds
},
hide = function(){
loading_dots.style.display = "none";
};
show();
})();
}
document.getElementById("myBtn1").addEventListener("click", myFunc);
document.getElementById("myBtn2").addEventListener("click", myFunc);

How to get image to original position

Fiddle:
https://jsfiddle.net/r73b14y5/3/
script works fine but cant get the image to slide back to the original location if another link is not clicked.
at the moment the image stays where ever it last hovered over, instead of only staying at a link if the new link was clicked. and sliding back to the original link if nothing is clicked.
Also whats the best way to delay the hover state so as the mouse flys over the element quickly it doesnt activate. hover intent.
HTML:
<div class="bblock1" style="height:100%;">
<div class="container">
<div class="bodymainMaxS">
<div class='tabbed_content'>
<div class='tabs'>
<div class='moving_bg'> </div>
<span class='tab_item tab_item_color'>OVERVIEW</span>
<span class='tab_item'>THE SCIENCE</span>
<span class='tab_item'>ORDER</span>
<span class='tab_item'>REPLACEMENT FILTERS</span>
</div>
</div>
</div>
</div>
<div class="bblock3" style="height:100%;">
<div class="container">
<div class="bodymainMaxS">
</div>
</div>
</div>
** key part of Script:**
$(".tab_item").mouseover(function() {
var $this = $(this);
$this.parent().find(".moving_bg").stop().animate({
left: $this.position()['left']
}, { duration: 300 });
});
rest of script
var TabbedContent = {
current: {i:null, obj:null},
init: function() {
$(".tab_item").click(function() {
$(".tab_item").removeClass("tab_item_color");
$(this).addClass("tab_item_color");
var $this = $(this);
TabbedContent.slideContent($this);
});
TabbedContent.current.i = 0;
TabbedContent.current.obj = $(".tabslider li").eq(0);
},
slideContent: function($obj) {
var $container = $obj.closest(".tabbed_content"),
$contentContainer = $('.bodymainMaxS'),
$tabslider = $contentContainer.find(".tabslider");
var i = $obj.index() - 1;
var $lis = $tabslider.find("li");
$new = $lis.eq(i);
if(i === TabbedContent.current.i) {
return;
}
$lis.hide().filter($new.add(TabbedContent.current.obj)).show();
var margin_1 = (i > TabbedContent.current.i) ? 0 : -$new.width();
var margin_2 = (i < TabbedContent.current.i) ? 0 : -$new.width();
$tabslider.stop().css({
marginLeft: margin_1 + "px"
}).animate({
marginLeft: margin_2 + "px"
}, 400);
TabbedContent.current.i = i;
TabbedContent.current.obj = $new;
}
}
TabbedContent.init();
Here is the complete JS fixed replace whole javascript with this one (you can test here with JSFiddle )
removed TabbedContent because that was not being used (if you need that you can always copy from your question)
var isTabSelected = false;
var lastSelectedTabLeftPos;
$(".tab_item").mouseover(function() {
var $this = $(this);
$this.parent().find(".moving_bg").stop().animate({
left: $this.position()['left']
}, { duration: 300 });
});
$( ".tab_item" ).mouseout(function() {
if(isTabSelected){
$(".moving_bg").stop().animate({
left: ""+lastSelectedTabLeftPos
}, { duration: 300 });
}else
{
$(".moving_bg").stop().animate({
left: "0"
}, { duration: 300 });
}
});
$(".tab_item").click(function() {
isTabSelected = true;
var $this = $(this);
lastSelectedTabLeftPos = $this.position()['left'];
});

Perform click on one div after the other

I hope you understand my problem.
At the moment I have a JS-function that choses randomly a div of a specific Html-Class.
Now i would like to rewrite the function that it picks one div after the other, just like they are ordered in the HTML-content.
How can I do this?
For information: the random selection is made with jquery and looks like this:
function pickrandom() {
var elems = $(".classname");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
console.log(keep);
$(elems[keep]).click();
}
}
Thanks
$(document).on('click', '.classname', function(){
var self = $(this);
var total_items = $('.classname').length; // 10
var index = self.index(); //2 for 3rd element
if (index < total_items) {
setTimeout(function () {
$('.classname').eq(index+1).trigger('click');
}, 3000);
}
});
this will call the next clicks in 3 sec interval
i don't know why you are using a randomizer function.you can allow the user to make that click
Hopefully this helps you - can't see your markup, but it should get you on the right track. I've also changed your .click() to a .trigger('click') which should be quite a bit more dependable.
JavaScript
function pickrandom() {
var elems = $(".classname");
if (elems.length) {
var curTarget = Math.floor(Math.random() * elems.length);
console.log(curTarget);
$(elems[curTarget]).trigger('click');
// Find index of our next target - if we've reached
// the end, go back to beginning
var nextTarget = curTarget + 1;
if( nextTarget > elems.length ) {
nextTarget = 0;
}
// Wait 3 seconds and click the next div
setTimeout( function() { $(elems[nextTarget]).trigger('click'); }, 3000 );
}
}
$("div").click(function() {
var el = $(this);
setTimeout(function() {
console.log(el.text());
el.toggleClass("click");
}, 2000);
});
var random = Math.floor((Math.random() * $("div").length) + 1);
var index = random - 1;
console.log("Random number: ", random);
var clicker = setInterval(function() {
if (index === $("div").length) {
clearInterval(clicker);
console.log("cleared interval");
} else {
$("div").eq(index).click();
index++;
}
}, 2000)
div {
height: 50px;
width: 100%;
border: 2px solid black;
background-color: lightgreen;
margin-bottom: 10px;
text-align: center;
font-size: 30px;
}
.click {
background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Div 1
</div>
<div>
Div 2
</div>
<div>
Div 3
</div>
<div>
Div 4
</div>
<div>
Div 5
</div>
<div>
Div 6
</div>

Why isn't it possible to change max-height with % in javascript?

I'm trying to build a responsive menu, with a hamburger icon. I want the menu list to slide in and out, no jquery - pure javascript only.
HTML :
<div id="animation">
</div>
<button id="toggle">Toggle</button>
CSS :
div {
width: 300px;
height: 300px;
background-color: blue;
}
Javascript :
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback){
var inter = -1, start = 100, end = 0;
if(type==true){
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function(){
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if(start == end){
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function(){
animate(hidden, function(){
hidden = (hidden == false) ? true : false;
});
}
div.style.maxHeight = "50%";
The problem is that proportional height in an element needs a fixed height on the parent, and you didn't provided any parent with a fixed height because for the maxHeight property too the % Defines the maximum height in % of the parent element.
You have to put your div in a parent container with a fixed height, this is your working code:
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function(type, callback) {
var inter = -1,
start = 100,
end = 0;
if (type) {
inter = 1;
start = 0;
end = 100;
}
var si = setInterval(function() {
console.log('maxheight');
div.style.maxHeight = (start + inter) + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
}
var hidden = false;
but.onclick = function() {
animate(hidden, function() {
hidden = !hidden ;
});
}
div.style.maxHeight = "50%";
#animation {
width: 300px;
height: 300px;
background-color: blue;
}
#parent {
width: 500px;
height: 500px;
}
<div id="parent">
<div id="animation">
</div>
<button id="toggle">Toggle</button>
</div>
Note:
As stated in comments there are some statements in your JavaScript code that need to be adjusted:
if(type==true) can be written as if(type).
hidden = (hidden == false) ? true : false; can be shortened to hidden = !hidden
There seems to be a few errors with your code. I have fixed the js and added comments to what I have changed
var but = document.getElementById('toggle');
var div = document.getElementById('animation');
var animate = function (type, callback) {
var start = 100,
end = 0;
if (type) {
start = 0;
end = 100;
}
var si = setInterval(function () {
if (type) { // check whether to open or close animation
start++;
} else {
start--
}
div.style.maxHeight = start + '%';
if (start == end) {
clearInterval(si);
}
}, 10);
callback.call(this); // do the callback function
}
var hidden = false;
but.onclick = function () {
animate(hidden, function () {
hidden = !hidden; // set hidden to opposite
});
}
/*make sure parent container has a height set or max height won't work*/
html, body {
height:100%;
margin:0;
padding:0;
}
div {
width: 300px;
height: 300px;
background-color: blue;
}
<div id="animation"></div>
<button id="toggle">Toggle</button>
Example Fiddle

Categories