Showing/hiding <div> using javascript - javascript

For example I have a function called showcontainer. When I click on a button activating it, I want a certain div element, in this case <div id="container">, to fade in. And when I click it again, fade out.
How do I achieve this?
Note: I am not accustomed with jQuery.

So you got a bunch of jQuery answers. That's fine, I tend to use jQuery for this kind of stuff too. But doing that in plain JavaScript is not hard, it's just a lot more verbose:
var container = document.getElementById('container');
var btn = document.getElementById('showcontainer');
btn.onclick = function() {
// Fade out
if(container.style.display != 'none') {
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity -= 5;
container.style.opacity = opacity/100;
if(opacity <= 0) {
clearInterval(fade);
container.style.opacity = 0;
container.style.display = 'none';
}
}, 50);
// Fade in
} else {
container.style.display = 'block';
container.style.opacity = 0;
var fade = setInterval(function(){
var opacity = parseFloat(container.style.opacity);
opacity = isNaN(opacity) ? 100 : parseInt(opacity * 100, 10);
opacity += 5;
container.style.opacity = opacity/100;
if(opacity >= 100) {
clearInterval(fade);
container.style.opacity = 1;
}
}, 50);
}
};
Check the working demo.

Provided you're not opposed to using jQuery per se, you can achieve this easily:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#showcontainer').click(function() {
$('#container').fadeToggle();
});
});
</script>
...
<div id="container">
...
</div>
...
<input type="button" id="showcontainer" value="Show/hide"/>
...
Note the missing http: in the beginning of the source of jQuery. With this trick the browser will automatically use http: or https: based on whether the original page is secure.
The piece of code after including jQuery assigns the handler to the button.

Best thing you could do is start now and get accustomed to jQuery.
The page http://api.jquery.com/fadeIn/ has all the example code that could be written here. Basically you want to have the call to fadeIn in your showcontainer function.
function showcontainer() {
$('#container').fadeIn();
}

You can have a look at jQuery UI Toggle.
The documentation turns the use of the library very simple, and they have many code examples.

You'd be as well off learning jQuery as it makes it a lot easier to do things!
From the sounds of it, you could have the container div already in the HTML but with a style of "display:none;", and then simply show it in your click event using (jQuery):
$('#container').fadeIn('slow', function() {
//Any additional logic after it's visible can go here
});

Related

CSS3 Slide Show Fade Effect not working

http://jsfiddle.net/pdb4kb1a/2/
The code works just fine on JSFiddle, but I cant get it to work when I use it in a HTML/CSS file. Only the 50x200 image is displayed, no signs of the simple slideshow or fade effect. I work in Sublime text, could that create any problems?
var imgArray = [
'http://placehold.it/300x200',
'http://placehold.it/200x100',
'http://placehold.it/400x300'],
curIndex = 0;
imgDuration = 3000;
function slideShow() {
document.getElementById('slider').className += "fadeOut";
setTimeout(function() {
document.getElementById('slider').src = imgArray[curIndex];
document.getElementById('slider').className = "";
},1000);
curIndex++;
if (curIndex == imgArray.length) { curIndex = 0; }
setTimeout(slideShow, imgDuration);
}
slideShow();
#slider {
opacity:1;
transition: opacity 1s;
}
#slider.fadeOut {
opacity:0;
}
<body>
<img id="slider" src="http://placehold.it/50x200">
</body>
JSFiddle executes the javascript code in the window.onload event. You can change this if you click the JavaScript Button in the editor of JSFiddle.
If you change it to No wrap - in <head> you'll see that it doesn't work as well. You should see an error in your console, telling you the reason.
I'm assuming that you're including your script snippet in the head section of your HTML Document.
If you take your code as posted in your question, your slider isn't loaded yet, because the script is executed before your HTML document is fully loaded. You have to wrap the call to your slideShow function inside the onloadevent (or if you're using jQuery you'll probably use $(document).ready(function(){ ... }) instead.
This should do the trick then:
window.onload = function() {
slideShow();
}
Including the script at the bottom of your HTML document should work as well as an alternative.

Wow.js repeat animation every time you scroll up or down

I'm pretty new with Jquery. I would like that my animations with Wow.js could run more than once time. For instance: i scroll to the bottom of my page and see all the animations, and if i scroll back to the top i see again the animations like when you scroll down. I hope that I explained myself. I have already seen many websites that repeats the animations on theirs pages but unfortunately I don't remember them and I can't provide a link.
I have already tried this:
$(window).scroll(function(){
new WOW().init();
}
But it repeat the animations also if you scroll a little and it's pretty ugly to see. I try to explain me better: I have a with my animation and if it is focused the animation is triggered, then i scroll down to another div and the previous div is no more visible(not in the window viewport), then again i scroll back to my div with animation and the animation is triggered again.
I'm sorry for this messy question but I really don't know how to explain it.
Thanks in advance!
This example by BenoƮt Boucart shows how the animation can be "reset" when the user scrolls out of view and back in. The key here is the second function that removes the animation css class when the element scrolls out of view. I wish WOW.js would implement this, but they've indicated that they don't plan to.
http://codepen.io/benske/pen/yJoqz
Snippet:
// Showed...
$(".revealOnScroll:not(.animated)").each(function () {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded > offsetTop) {
if ($this.data('timeout')) {
window.setTimeout(function(){
$this.addClass('animated ' + $this.data('animation'));
}, parseInt($this.data('timeout'),10));
} else {
$this.addClass('animated ' + $this.data('animation'));
}
}
});
// Hidden...
$(".revealOnScroll.animated").each(function (index) {
var $this = $(this),
offsetTop = $this.offset().top;
if (scrolled + win_height_padded < offsetTop) {
$(this).removeClass('animated fadeInUp flipInX lightSpeedIn')
}
});
If a user wants to repeat the animation on both the events i.e.
onScrollUp
onScrollDown
then this will be a good solution for it:
First create an addBox function, it will help to push new elements into the WOW boxes array.
WOW.prototype.addBox = function(element){
this.boxes.push(element);
};
Then use jQuery and scrollspy plugin that helps to detect which element is out of the view and then push WOW as:
$('.wow').on('scrollSpy:exit',function(){
var element = $(this);
element.css({
'visibility' : 'hidden',
'animation-name' : 'none'
}).removeClass('animated');
wow.addBox(this);
});
Solution Courtesy: ugurerkan
Answer by #vivekk is correct I m just adding a working example so that people can easily get this
see the Demo fiddle
<script>
// Repeat demo content
var $body = $('body');
var $box = $('.box');
for (var i = 0; i < 20; i++) {
$box.clone().appendTo($body);
}
// Helper function for add element box list in WOW
WOW.prototype.addBox = function(element) {
this.boxes.push(element);
};
// Init WOW.js and get instance
var wow = new WOW();
wow.init();
// Attach scrollSpy to .wow elements for detect view exit events,
// then reset elements and add again for animation
$('.wow').on('scrollSpy:exit', function() {
$(this).css({
'visibility': 'hidden',
'animation-name': 'none'
}).removeClass('animated');
wow.addBox(this);
}).scrollSpy();
</script>

Javascript hide and show a div in a loop for a text "blink" effect

I recently wanted to make a element in a div with the ID of "test" to have a "blink" effect like most text editors have where the cursor is hidden and then shown, then hidden and shown....(in a loop) I tried to recreate this effect but just couldn't get it to work. Please help!
Here is some code:
<div id="test">
<p> _ </p>
</div>
Something like this?
setInterval(function(){
$("#test p").toggle();
},3000);
blinks every 3 seconds.
Here's a concise, pure JavaScript way.
blink = setInterval(function () {
element = document.querySelector("#test p");
element.style.opacity = (element.style.opacity == 1 ? 0 : 1);
}, 500);
If you want to stop it, run clearInterval(blink).
Here's a working fiddle.
FIDDLE
setInterval(function(){
$("#test p").toggle();
},300);
Here is an example using Javascript
setInterval(function(){
var elem = document.querySelector("#test p");
if(isVisible(elem)) {
elem.style.display = 'none';
} else {
elem.style.display = 'block';
}
},500);
function isVisible(elem) {
return elem.offsetWidth > 0 || elem.offsetHeight > 0;
}
(Though knouroozi's answer will stop the contents from shifting around, so I'd suggest that.)
With JQuery it becomes simpler:
setInterval(function(){
$('#test p').toggle();
},500);
(stckrboy's answer covers toggling visibility, rather than 'display', which will prevent the content from shifting around.)
Here's an example using jQuery and setInterval
$(".crsr").each(function(){
var elem=$(this);
setInterval( function() {
if(elem.css('visibility')=='hidden') {
elem.css('visibility','visible')
} else {
elem.css('visibility','hidden')
}
},500)
});
jSFiddle
Throwing my approach into the ring. :) Set up a class that changes the visibility to hidden and then use setInterval and toggleClass to toggle the class off and on.
HTML
<div id="blinkingText">
Blink for me!
</div>
CSS
<style>
.blinkOn {visibility: hidden;}
</style>
JS
<script type="text/javascript">
$(document).ready(function(){
setInterval(function() {
$("#blinkingText").toggleClass("blinkOn");
},1000);
});
</script>

How to make a Div's height change slower

I want to make a Div appear by scrolling down on a button click slowly from the top of the page. But when I do it with what I have now, it just appears very fast and does not really slide down. What am I doing wrong?
function showstuff(inquiryForm){
document.getElementById(inquiryForm).style.visibility="visible";
for (var i=0;i<300;i++)
{
document.getElementById(inquiryForm).style.height= i + "px";
}
}
You are looping 300 items and you try to find the element with getELementById and then trying to style the selected item
I think that makes the process really slow and laggy.
Here is an example that should help you understand the event loop,
and the use of setTimeout.
<div id="myDiv" style="width:10px;height:50px;background:#f00;"></div>
<button class="btn" onclick="start();">Start</button>
<button class="btn" onclick="stop();">Stop</button>
<button class="btn" onclick="reset();">Reset<button>
var timeout;
function start() {
var div = document.getElementById("myDiv");
var size = 10;
var func = function () {
timeout = setTimeout(func, 0);
div.style.width = size + "px";
if (size++ == 600) stop();
}
func(); // starts the process
}
function stop() {
clearInterval(timeout);
}
function reset() {
var div = document.getElementById("myDiv");
div.style.width = "10px";
}
this sort of thing is often handled using jquery, as it includes various animation functions, including a convenient short form that would be useful here:
once you've included the jquery library, you can use a function like this:
$(inquiryForm).slideDown( 500 );
where the argument is duration of the effect in ms
like so:
function showstuff(inquiryForm){
$(inquiryForm).slideDown( 500 );
}

javascript change image slowly with fade using timer and opacity

i am looking for some help with this script i have been working on. here is my file fade.js
the problem is with the changing, it is messed up. please help me find the problem and solution for this, thanks.
JS-file
//image fade script
var opacity = 0;
function changeimg(currentimage){
rnumb = Math.floor(Math.random()*2);
var newimage = "./images/" + rnumb + ".jpg";
if (newimage !== currentimage)
{
document.getElementById("fadeImg").src= newimage;
}
}
function fadein()
{
var fadeImg = document.getElementById('fadeImg');
var browserName=navigator.appName;
if(browserName=="Microsoft Internet Explorer")
{
browserOpacity = opacity / 10;
fadeImg.filters.alpha.opacity = browserOpacity;
}
else
{
browserOpacity = opacity / 1000;
fadeImg.style.opacity = browserOpacity;
}
if(opacity < 1000)
{
initiate();
}
else if(opacity == 1000)
{
changeimg(document.getElementById("fadeImg").src);
opacity = 0;
}
}
function initiate()
{
opacity++;
setInterval("fadein()", 500);
}
index.html
<script type="text/javascript" src="fade.js"></script>
<body onload="initiate()">
<img id="fadeImg" src="images/1.jpg" style="opacity:0.0; filter:alpha(opacity=0)"/>
</body>
JS-fiddle
Here is a Fiddle of the code as well: http://jsfiddle.net/epqKr/2/ (Notice that the code, as it is in the fiddle, may make your browser freeze after a while.
I think you should use a cross-browser library to accomplish things like this.
Microsoft Internet Explorer, especially in versions < 9, is most likely to not behave
as you would expect it does, particularly when you try to use functions which makes use of opacity, alpha-filter and timing. You could try to use jQuery, or Prototype, or MooTools and such frameworks. They all make what you're looking for in simple, secure, better way.
Don't call initiate() from within the fadeIn() function, instead just increment your opacity control variable (i.e, opacity += 1;).
You will probably want to save your setInterval return value to kill the callbacks when you have finished your animation.
You also probably will want to increase the animation speed by lowering the interval.
animId = setInterval("fadeIn()", 5);
i am working on this still, heres what i have now: it doesnt work whatsoever but it looks better.
html
<html>
<head>
<script type="text/javascript" src="fade1.js"></script>
</head>
<body onload="fadetimer()">
<img id="fadeImg" src="1.jpg" style="opacity:0.0; filter:alpha(opacity=0)"/>
</body>
</body>
</html>
script
//image fade script
var opacity = 0;
function changeimg(currentimage){
rnumb = Math.floor(Math.random()*2);
var newimage = rnumb + ".jpg";
if (newimage !== currentimage)
{
document.getElementById("fade").src= newimage;
}
}
function fadein()
{
var fade = document.getElementById('fade');
if(fade.filters.alpha.opacity >= 100 || fade.style.opacity >= 1.0)
{
changeimg(fade.src);
fade.filters.alpha.opacity = 0;
fade.style.opacity = 0;
}
else
{
fade.filters.alpha.opacity += 10;
fade.style.opacity += 0.1;
}
}
function fadetimer()
{
setInterval("fadein()", 500);
}

Categories

Resources