Fade HTML element with raw javascript - javascript

It's my second question of the day related to the same problem, so I apologize for that.
I was able to put together a function to "fade out" an element, and it works just fine, my problem is that when I try to reverse it, so the element "fades in" it does not work.
I've tried to change the obvious, but I can't understand what I'm doing wrong.
My code so far is as follows:
Given I have a "div" like so:
<div id="test" style="width:200px; height:200px; display:block; opacity:1; background-color:red;"></div>
The JavaScript function that I'm using to fade it out is:
var getElement = document.getElementById('test');
function fadeOut(elem, speed){
if(!elem.style.opacity){
elem.style.opacity = 1;
}
var desvanecer = setInterval(function(){
elem.style.opacity -= .02;
if(elem.style.opacity < 0){
clearInterval(desvanecer);
}
}, speed / 50);
}
fadeOut(getElement, 500);
Could somebody take a look at this and let me know what I'm doing wrong, all I want to do is "FADE IN" an element to an opacity equal to "1".
By the way, I can't use jQuery, however I'm eager to learn this way.
Thanks
My attemp to reverse the function is as follows:
var getElement = document.getElementById('test');
function fadeIn(elem, speed){
if(elem.style.opacity){
elem.style.opacity = 0;
}
var desvanecer = setInterval(function(){
elem.style.opacity += .02;
if(elem.style.opacity > 1){
clearInterval(desvanecer);
}
}, speed / 50);
}
fadeIn(getElement, 500);

setInterval runs in a global scope, so you need to define the timer relative to the window.
You can't concatinate the string value returned from the style property and
expect a number- you'll get '0.02.02.02.02'
Coerce a number out of the string, then add the .02.
It will work in some browsers, but IE before 9 needs a different expression
to set and read opacity.
function fadeIn(elem, speed){
if(elem.style){
elem.style.opacity= '0';
}
window.fadetimer= setInterval(function(){
elem.style.opacity= +(elem.style.opacity)+.02;
if(elem.style.opacity> 1){
clearInterval(fadetimer);
}
},
speed);
}

Related

How to change the opacity on an element dynamically using javascript

i made a function that change the opacity of an element, but you know it is not working, Following is my code:
function _opacity(ele, opacity,addOpac , delay ){
ele = document.getElementById(ele);
var CurrentOpacity = ele.style.opacity,
ChangeInOpacity = setInterval(function(){
if (CurrentOpacity > opacity ) { decrease();};
if (CurrentOpacity < opacity) { increase();};
if (CurrentOpacity == opacity) { stopInc();};
}, delay),
increase = function(){
ele.style.opacity = CurrentOpacity;
CurrentOpacity = CurrentOpacity+addOpac;
},
decrease =function(){
ele.style.opacity = CurrentOpacity;
CurrentOpacity = CurrentOpacity-addOpac;
},
stopInc = function(){
clearInterval(ChangeInOpacity);
};
}
one of the foremost feature of this function is that is doesn't uses any loop.
this ideology of using setInterval works perfectly in changing the width and height of element. But here this function is not functioning.
What i know is that it is not adding any style attribute to the element which is passed to the above function
what is the mistake here because of which this is not working?
thanks in advance.
There are a few problems there:
To get the current opacity of the element, you need to use the getComputedStyle function (or currentStyle property on oldIE), not .style.opacity. The latter only has a value if it's been assigned explicitly, rather than implicitly through style sheets.
The value will be a string, so you need to convert it to a number.
It's unlikely that you'll exactly match the target opaccity, so you need to just stop when you cross the target.
You don't put ; at the end of if statements, so remove those.
You assign the opacity, but then increment it, and then later the incremented value is what you check to see if you're done, so even if it weren't for #3, you'd stop early.
In JavaScript, the overwhelming convention is to start local variable names with a lower-case letter. I changed the name of your timer handle to timer.
Your best bet is to figure out what direction you're going, then stop when you pass the target:
// Polyfill getComputedStyle for old IE
if (!window.getComputedStyle) {
window.getComputedStyle = function(element) {
return element.currentStyle;
}
}
// Your _opacity function
function _opacity(ele, opacity, addOpac, delay) {
var direction;
ele = document.getElementById(ele);
// Determine direction
direction = +getComputedStyle(ele).opacity < opacity ? 1 : -1;
var timer = setInterval(function() {
// Get the *computed* opacity
var current = +getComputedStyle(ele).opacity;
if (direction > 0) {
if (current < opacity) {
increase(current);
} else {
stopInc();
}
}
else {
if (current > opacity) {
decrease(current);
} else {
stopInc();
}
}
}, delay),
increase = function(current) {
// Increase, but don't go past target
ele.style.opacity = Math.min(current + addOpac, opacity);
},
decrease = function(current) {
// Decrease, but don't go past target
ele.style.opacity = Math.max(current - addOpac, opacity);
},
stopInc = function() {
clearInterval(timer);
};
};
// Run
_opacity("target", 0.3, 0.05, 50);
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div id="target">this is the element</div>
you can do this:
ele.style.opacity = "0.2";// some desired value but string if for all browsers.
for more info see this post:Setting opacity of html elements in different browsers

Fade in using plain javascript

Trying to do a simple fade in using the opacity property of an h1 element. I'm learning javascript, so would like to try this using plain javascript (yes, I know it is much easier using jQuery).
Pasting only relevant snippets:
<body onload="fadeIn()">
...
<div class = "container">
<div class = "row">
<div class = "col-md-3">
<img class = "img-responsive" src="icons/Website_Logo.png">
</div>
<div class = "col-md-9 page-header">
<h1 id="welcomeHeader" style="opacity:0">
Welcome to the world!
</h1>
</div>
</div>
</div>
...
<script>
function fadeIn() {
var el = document.getElementById("welcomeHeader");
var op = parseFloat(el.style.opacity);
var timer = (function () {
if(op >= 1.0)
clearInterval(timer);
op += 0.1;
el.style.opacity = op;
}, 50);
}
</script>
</body>
Help is much appreciated! Thanks!
jsFIDDLE
You need to call the setInterval function first in order to invoke a timer. Rest is fine. Here is a working fiddle
Code Snippet:
function fadeIn() {
var el = document.getElementById("welcomeHeader");
var op = parseFloat(el.style.opacity);
var timer = setInterval(function () {
console.log('here');
if(op >= 1.0)
clearInterval(timer);
op += 0.1;
el.style.opacity = op;
}, 50);
}
You need to change your function to use setInterval like so:
var timer = setInterval(function () { // notice the setInterval added.
if(op >= 1.0)
clearInterval(timer);
op += 0.1;
el.style.opacity = op;
}, 50);
Notes:
I give you this answer to help you LEARN javascript as you mentioned, otherwise,
it would be better done with pure css of course.
Also, make sure your opacity is set to 0 in your css as a starting point.
You don't need a timer for this - all you need to do is change the class. Here's an example:
the CSS:
element{
/* whatever styles you have */
}
element_faded{
transition: opacity .5s;
opacity: 50%; /* or whatever values you want */
}
the javascript
var element = document.getElementById('element');
// in order to trigger the fade, just change the class
element.className = "element_faded";
In the transition will happen between the values of the original and new class, so if you want a fade-in, have the original opacity be 0% and the new one be 100% or something higher than zero, depending on what you want the final opacity to be. Also, remember that the transition characteristics are determined by the transition attribute in the new class.
Doing this without CSS will just make things more complicated unless you need to do something more sophisticated than just plain fading in or out. If that's the case, then use setInterval or perhaps even something like requestAnimationFrame if you're feeling adventurous.
Honestly, this isn't really the kind of thing you need to learn when first learning javascript. Eventually this will be really easy once you get some confidence under your belt doing things that work more easily in javascript (setTimeout and the like can have their own weird caveats). Try to set a meaningful, practical goal and fulfill it first, using whatever mix of javscript/css/html you can and you'll soon have the basics down well enough to find things like this obvious.

jQuery fade in box with unique content

I am making an info screen, and for that, it needs to show reviews from their customers pulled from Trustpilot.
I got the reviews and everything formatted in HTML showing the 20 latest, but I want to present it very sweet. I am not a JavaScript guru, but I thought i would do it using jQuery and its fadein function.
What is want, is have 20 unique divs fading in with X milliseconds difference popping randomly up. By unique I mean, that each div must have unique content. And by randomly popping up, I mean that if box 1 spawns first, then the next should be 5, then 14 etc, and then another cycle the next time around.
Just like what I made here;
$(function() {
var box = $('.box');
var delay = 100;
for (i = 0; i < 30; i++) {
setTimeout(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}
});
http://jsfiddle.net/CCawh/5/
Is this even possible, and how would this be done?
I am very new to JavaScript, so please bear with me if I ask to much
Thanks in advance.
EDIT:
The HTML i want to spawn will all be wrapped in divs, so it would go like this;
<div id="one">content</div>
<div id="two">content</div>
<div id="three">content</div>
<div id="four">content</div>
etc.
Made up a nice function for you. I believe this may be what you are looking for
Here's a rundown of how it works :
Populate an array with numbers randomly generated 1-10 in this case.
Run through that array with a set interval, and when everything has
been added stop the interval
pretty straightforward from there. Set the visibility etc. You should be able to change up the function to dynamically add HTML elements and what-not, but just giving you something to start with.
var usedNum = [];
var i, j, y;
i = 0;
for(y = 0; y < 10; y++){
var x = Math.floor((Math.random() * 10) + 1);
if(!isUsed(x)) usedNum.push(x);
else y--;
}
var showInterval = setInterval ( function(){
if(i == 10){
clearInterval(showInterval);
}
$(".container div[data-line='" + usedNum[i] + "']").css({opacity: 0.0, visibility: "visible"}).animate({opacity: 1.0});
i++;
}, 500);
function isUsed(num) {
var used = false;
for(j = 0; j < usedNum.length; j++){
if(usedNum[j] == num){
used = true;
}
}
return used;
}
Demo fiddle : http://jsfiddle.net/xS39F/3/
Edit:
You can also mess around with the speed of the animation. In this demo (http://jsfiddle.net/adjit/XYU34/1/) I set the speed to 1000 so the next element starts fading in before the last element was done fading in. Makes it look a little smoother.
Instead of using a for loop and setTimeout, would setInterval work better for what you need? Some HTML might help better understand what you're trying to achieve.
$(function() {
var box = $('.box');
var delay = 100;
var interval = setInterval(function() {
var new_box = box.clone();
$('.container').append(new_box);
new_box.fadeIn();
}, delay);
delay += 500; // Delay the next box by an extra 500ms
}, delay);
});

showing random value in div element with javascript

I want my div element to work like a timer and shows random numbers with an interval of 1s. http://jsfiddle.net/NHAvS/46/. That is my code:
var arrData = [];
for (i=0;i<1000;i++)
{
arrData.push({"bandwidth":Math.floor(Math.random() * 100)});
}
var div = document.getElementById('wrapper').innerHTML =arrData;
document.getElementById('wrapper').style.left = '200px';
document.getElementById('wrapper').style.top = '100px';
but the problem is that it only shows 1 data at a time. any idea how to fix it?
Thanks
Do this:
setInterval(myfun,1000);
var div = document.getElementById('wrapper');
function myfun(){
div.innerHTML ='bandwidth :'+Math.floor(Math.random() * 100);
}
Take a Look: http://jsfiddle.net/techsin/NHAvS/49/
Note: your example was messed up as on left side it was set to load in head which means your div would be undefined every time your script loads before your dom. so setting it to onload make it works little more. :D
Note: also you seem to be chaining functions as in jquery, but in javascript you don't do that. The functions are made to do that. i.e. div= ..getElementById..innerHtml='balbla'; would set div = bla... not element.
You're better off using jQuery and CSS to achieve your desired result. jQuery to find the element and to display the random number; and CSS instead of manually setting the position. (Obviously jQuery is just a personal choice and document.getElementById will suffice - but if you're planning on manipulating the DOM a lot, jQuery is probably a better route to take). See updated fiddle
$(function () {
var arrData = [];
for (i = 0; i < 1000; i++) {
arrData.push({
"bandwidth": Math.floor(Math.random() * 100)
});
}
var index = 0;
setInterval(function(){
$("#wrapper").text(arrData[index].bandwidth);
index++;
}, 1000);
});
You can do it like this:
var delay = 1000, // 1000 ms = 1 sec
i;
setTimeout(function() {
document.getElementById('wrapper').innerHTML = arrData[i];
i++;
}, delay);

Difficulty with setInterval loop using class of Divs

$(document).ready(function fadeIt() {
$("#cool_content > div").hide();
var sizeLoop = $("#cool_content > div").length;
var startLoop = 0;
$("#cool_content > div").first().eq(startLoop).fadeIn(500);
setInterval(function () {
$("#cool_content > div").eq(startLoop).fadeOut(1000);
if (startLoop == sizeLoop) {
startLoop = 0
} else {
startLoop++;
}
$("#cool_content > div").eq(startLoop).fadeIn(1500);
}, 2000);
});
Here I want a class of divs to animate, infinitely!
However, because the interval is set to two seconds there is period where no div is showing!
What would be an appropriate way to loop the animation of these divs?
I thought about using a for loop but couldn't figure out how to pass a class of divs as arguments. All your help is appreciated.
Thanks!
Ok, generally, you should know that Javascript is a single threaded environment. Along with this, the timer events are generally not on time accurately. I'm not sure how jQuery is doing fadeIn and fadeOut, but if it's not using CSS3 transitions, it's going to be using timeOut and Intervals. So basically, there's a lot of timer's going on.
If you go with the for loop on this one, you'd be blocking the single thread, so that's not the way to go forward. You'd have to do the fade in/out by yourself in the setInterval.
Setting the opacity on each interval call. Like div.css('opacity', (opacity -= 10) + '%')
If you're trying to fade in and out sequentially, I think maybe this code would help
var opacity = 100,
isFadingIn = false;
window.setInterval(function() {
if (isFadingIn) {
opacity += 10;
if (opacity === 100) isFadingIn = false;
} else {
opacity -= 10;
if (opacity === 0) isFadingIn = true;
}
$('#coolContent > div').css('opacity', opacity + '%');
}, 2000);
Consider the following JavaScript / jQuery:
$(function(){
var divs = $('#cool_content > div').hide();
var curDiv;
var counter = 0;
var doUpdate = function(){
// Hide any old div
if (curDiv)
curDiv.fadeOut(1000);
// Show the new div
curDiv = divs.eq(counter);
curDiv.fadeIn(1000);
// Increment the counter
counter = ++counter % divs.length;
};
doUpdate();
setInterval(doUpdate, 2000);
});
This loops infinitely through the divs. It's also more efficient than your code because it only queries the DOM for the list of divs once.
Update: Forked fiddle
instead of
if (startLoop == sizeLoop)
{
startLoop = 0
}
else
{
startLoop++;
}
use
startLoop =(startLoop+1)%sizeLoop;
Check the demo http://jsfiddle.net/JvdU9/ - 1st div is being animated just immediately after 4th disappears.
UPD:
Not sure I've undestood your question, but I'll try to answer :)
It doesn't matter how many divs you are being looped - 4, 5 or 10, since number of frames are being calculated automatically
x=(x+1)%n means that x will never be greater than n-1: x>=0 and x<n.
x=(x+1)%n is just shorten equivalent for
if(x<n-1)
x++;
else
x=0;
as for me first variant is much readable:)
And sorry, I gave you last time wrong demo. Correct one - http://jsfiddle.net/JvdU9/2/

Categories