Make text flicker usinf Vanilla JS - javascript

Now I want my text to flicker jus like a tube light. This means there should be some noise in its blinking. it should not be a set definite interval in which opacity changes.
Here is what I came up with:
//find the text i want to flicker
text = document.getElementById("flicker");
console.log(text);
//initialise with 0
text.style.opacity=0;
//logic of wait function
function wait(ms){
var start = new Date().getTime();
var end = start;
while(end < start + ms) {
end = new Date().getTime();
}
}
while(true){
//logic to invert the opacity
if(text.style.opacity=1)
text.style.opacity=0;
else if (text.style.opacity=0)
text.style.opacity=1;
//find a random time interval b/w 0 to 0.5 sec
randVal = Math.random()*500+1;
//wait of that time and repeat the process for ever
wait(randVal);
}
Now the problem comes when I load the web page.
IT DOES NOT LOAD
MY GUESS: the infinite while loop is the problem and is running even before the DOM loads
but I have added the script at the end of my HTML file

Use a setTimeout and toggle a class instead.
//find the text i want to flicker
const text = document.getElementById("flicker");
console.log(text);
const getDuration = () => {
//find a random time interval b/w 0 to 0.5 sec
const randVal = Math.random()*500+1;
console.log(randVal);
return randVal;
};
const doFlicker = () => {
//logic to invert the opacity
text.classList.toggle('clear');
setTimeout(doFlicker, getDuration());
};
setTimeout(doFlicker, getDuration());
.clear {
color: #00000000;
}
<div id="flicker" class="clear">Flicker</div>

Related

Is there a way to run a line of code after a marquee has finished scrolling once?

Is there a way to run a line of code after a marquee has finished scrolling its text one time? I was going to use it to whenever the text was gone I would remove the element in the queue index with the location of 0 and then use the marquee to show the next element in the queue. How would I do this?
I'm kinda new to coding, so please excuse me if this is a bad question to ask.
let scroller = document.getElementById("scrollText")
let news = function (news, id) {
this.text = news;
this.id = id;
}
let newsFeed = [
new news("Bob has slipped and fell once again. Oh dear.", 1),
new news("Alicia has lost her keys.", 2)
]
let queue = []
scroller.innerHTML = queue[0]
queue.append(newsFeed[Math.round(math.random) * newsFeed.length])
//Whenever the marquee is done scrolling
queue.pop()
scroller.innerHTML = queue[0];
as #WoIIe suggest you can check on the marquee element left position to find out if its finished scrolling, try doing somthing like this :
$(function () {
var numberofCycles = 0;
setInterval(function () {
var currentLeft = $('#scrollText').position().left;
if (currentLeft < 0 && numberofCycles == 0) {
numberofCycles += 1;
alert("One cycle finished!");
}
}, 100)
});

Jquery hover efect in loop

I have list of projects with images that have hover effect. Hover effect shows project description. I made a loop that shows for 3 seconds every project description.
The problem is when you mouse enter some element it shows text, but when loop catches it hides project text. And you need leave and enter the element to show text again. I want to prevent from text to hide if element is already hovered.
var index = 0;
var duration = 3000;
function loopProjects() {
$('.port-hov').each(function(index,item) {
index = index + 1;
//console.log(index);
setTimeout(function(){
$(item).mouseenter();},duration);
duration = duration + 3000;
setTimeout(function(){
$(item).mouseleave();},duration);
});
}
setInterval(loopProjects, index * 4000);
Solution!
function loopProjects() {
$('.port-hov').each(function(index,item) {
index = index + 1;
setTimeout(function(){
$(item).mouseenter();},duration);
duration = duration + 3000;
setTimeout(function(){
if (!$(item).is(":hover")){
$(item).mouseleave();}},duration);
});
}

Execute jQuery function after first is complete

I have created a page where I have multiple functionality done but stuck with timing of it, if you see the page example here in JSFiddle.
When you open the page, it will first run a loader and when the loader is complete there are multiple boxes, which is showing one by one but in currently its not happening, Loader is loading fine and then in the next step where centered columns has to appear one by one, the first four columns loads by default and then other div loads one by one.
My question is, how can I execute a function and execute another another function once the previous is complete.
For loader I have the following:
//--------- process bar animation
var showText = function (target, message, index, interval) {
if (index < message.length) {
$(target).append(message[index++]);
setTimeout(function () { showText(target, message, index, interval); }, interval);
}
}
var width = 100,
perfData = window.performance.timing, // The PerformanceTiming interface represents timing-related performance information for the given page.
EstimatedTime = -(perfData.loadEventEnd - perfData.navigationStart),
time = parseInt((EstimatedTime/1000)%60)*100;
showText("#msg", "Welcome to the Company Group", 0, width);
// Loadbar Animation
$(".loadbar").animate({
width: width + "%"
}, time);
// Loadbar Glow Animation
$(".glow").animate({
width: width + "%"
}, time);
// Percentage Increment Animation
var PercentageID = $("#precent"),
start = 0,
end = 100,
durataion = time;
animateValue(PercentageID, start, end, durataion);
function animateValue(id, start, end, duration) {
var range = end - start,
current = start,
increment = end > start? 1 : -1,
stepTime = Math.abs(Math.floor(duration / range)),
obj = $(id);
var timer = setInterval(function() {
current += increment;
$(obj).text(current + "%");
//obj.innerHTML = current;
if (current == end) {
clearInterval(timer);
}
}, stepTime);
}
// Fading Out Loadbar on Finised
setTimeout(function(){
$('.preloader-wrap').fadeOut(300);
$('.loader-wrap').fadeOut(300);
$('.main-wrapper').fadeIn(300);
$('body').addClass('bg');
}, time);
For showing div one by one in next step I have the following code:
$(".column-wrapper").each(function(index) {
var $this = $(this);
setTimeout(function () { $this.addClass("show"); }, index * 1000);
});
I use trigger and on for those kind of things. You had a lot of code, so sorry, I didn't want to read all of that but this is a simplified example.
https://jsfiddle.net/2d6p4L6k/1/
$(document).ready(function(){
var action = function(){
$('div.one').css('background-color', 'green');
/* do whatever you want to do */
/* then trigger(call) another function */
$(document).trigger('hello-action');
};
var hello = function() {
$('div.two').css('background-color', 'fuchsia');
};
/* just listen if anything triggers/calls "hello-action" */
/* if so call function named hello */
$(document).on('hello-action', hello);
setTimeout(action, 1500);
});
div {
width: 50px;
height: 50px;
background-color: orange;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">one</div>
<div class="two">two</div>
Note: To keep it simple we trigger and listen on $(document) which is really just to keep it simple. A better approach would be to have a wrapper element, and then you can do exactly the same (trigger and listen) just on that element and not on the entire document. You can find more details on the jQuery API .trigger()

javascript, div blinking instead of fading

I'm making a site that has an area that it's content disappear and re-appears. So when the user clicks certain button, the <div>'s content fades out and fades in the content relative to the clicked icon.
First time the function getabout is clicked it works OK, but whenever I click on clear() and then again on getabout it starts blinking. I've discovered that it does the clean to the div but it happens that the content re-appears again from nothing and becomes intermittent.
Here is my JavaScript code, it's commented so you could give me a hand here:
var check = null; //this will be checking the instance of div's content
const wait_time = 50; //the time it will take to fade
function getabout(id) {
/* prevent second call to the same function to bug */
if (check == id) return;
var titleOpacity = 0,
textOpacity = 0;
/* this changes the title first */
document.getElementById("title").style.opacity = 0;
document.getElementById("title").innerHTML = "this is the title";
// recursive call to the opacity changer, it
// increases opacity by 0.1 each time until it's 1
setInterval(function () {
titleOpacity = fadeIn(titleOpacity, 'title');
}, wait_time);
/* changes the content next to the title */
window.setTimeout(function () {
document.getElementById("dialog").style.opacity = 0;
document.getElementById("dialog").innerHTML = "this is the content";
setInterval(function () {
textOpacity = fadeIn(textOpacity, 'dialog');
}, wait_time);
}, 500);
check = id; // defines the instance "about" at the moment
}
function fadeIn(opacity, id) {
opacity += 0.1;
document.getElementById(id).style.opacity = opacity;
document.getElementById(id).style.MozOpacity = opacity;
if (opacity >= 1.0) clearInterval(listener);
return opacity;
}
function clear() {
var opacity = document.getElementById("title").style.opacity;
// supposed to decrease the opacity by 0.1 but it's not doing that
setInterval(function () {
opacity = fadeout(opacity);
}, wait_time);
//cleans the title and dialog to fill with the next button user clicked
document.getElementById("title").innerHTML = "";
document.getElementById("dialog").innerHTML = "";
}
function fadeout(opacity) {
opacity -= 0.1;
document.getElementById("title").style.opacity = opacity;
document.getElementById("dialog").style.MozOpacity = opacity;
if (opacity <= 0.0) clearInterval(listener);
return opacity;
}
function getregister(id) {
if (check == id) return;
clear(); // proceed to fade out the content and clean it
check = id;
}
I don't understand what is the error of the code. with the clear() function it should smoothly fade out the content and then clean it. But it just cleans the div. And next time I use getabout() function, instead of smoothly fade in again as it does the first time, it starts to blink.
I'm relatively new to web programming and I refuse JQuery for now. I want to understand deeply javascript before go to JQuery and this is why I would just like to know pure JavaScript solutions and considerations about this.
Ive managed to cock up my comment so trying again!
I think your problem is that you're not clearing the setInterval correctly - ensure you use listener = setInterval(...)
As it stands your clearInterval(listener); is doing nothing as 'listener' is not defined. So your fade out function continues to run.

Switch between 10 divs but return to the first div after a few seconds on no mouse move

I have 9 links in my header and 10 divs in the body. The first div is the main page, the other 9 divs have diffrent content in them. What i want to do is when people mouseover the 9 links it shows the 1 of the 9 divs. But if the user stops using the mouse it needs to return to the first div after 5 minutes.
I hope somebody can help me to set this up.
How about something like this?
// call showPage('something') to switch to a different section
var currPage = 'main';
function showPage(id) {
if (currPage !== null) {
document.getElementById(currPage).style.display = 'none';
}
currPage = id;
document.getElementById(currPage).style.display = 'block';
}
var lastMove = new Date().getTime();
document.onmousemove = function() {
lastMove = new Date().getTime();
}
setInterval(function() {
var now = new Date().getTime();
if (now - lastMove > 300000) {
showPage('main');
}
}, 5000);
We keep a global lastMove variable that gets updated with the current timestamp every time the mouse moves.
Then we have a function that's called every 5 seconds that can do something if it's been 5 minutes since the last time the mouse moved.
This is an alternate solution that involves setting up a new timer every time the mouse moves.
function goToMain() {
// todo: switch back to Main
}
var timer = null;
document.onmousemove = function {
if (timer !== null) clearTimeout(timer);
timer = setTimeout(goToMain, 300000);
}
This is slightly cleaner code than my first solution, but it's doing more processing on every mouse move, so it may not be as efficient.
You can make all the divs with absolute position and just play with style.visibility switching it from "hidden" to "visible". As for 5 minutes and back to div 1 - you can make timer function and onMouseMove just reset counter.
<header>
<script type='text/javascript'>
var maxTime = 300;//sec=5min
var offTime = 0;
document.documentElement.onmousemove = function(){offTime=0};
function isTimeToReturn(){
offTime++;
if(offTime<=maxTime){
setTimeout('isTimeToReturn',1000);
}else{
//change your present div to hidden and first to visible
}
}
setTomeout('isTimeToReturn',1000);
</script>
</header>

Categories