html button for fadeIn and FadeOut - javascript

Hey guys I'm making my own website just for fun and the following code makes a list of shapes appear. Does anyone know how I could incorporate another button instead of the fadeOut code to make it so that when I click another button, a "hide menu" button. The shapes will fadeOut. This is because the code I have at the moment means that the shapes will fade out by themselves over time. Pls help!
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1aside").fadeIn(100);
$("#div2aside").fadeIn(200);
$("#div3aside").fadeIn(300);
$("#div4aside").fadeIn(400);
$("#div5aside").fadeIn(500);
$("#div6aside").fadeIn(600);
$("#div7aside").fadeIn(700);
$("#div8aside").fadeIn(800);
$("#div9aside").fadeIn(900);
$("#div10aside").fadeIn(1000);
$("#div11aside").fadeIn(1100);
$("#div12aside").fadeIn(1200);
$("#div13aside").fadeIn(1300);
$("#div14aside").fadeIn(1400);
$("#div15aside").fadeIn(1500);
$("#div16aside").fadeIn(1600);
$("#div17aside").fadeIn(1700);
$("#div18aside").fadeIn(1800);
$("#div1aside").fadeOut(17670);
$("#div2aside").fadeOut(17660);
$("#div3aside").fadeOut(17650);
$("#div4aside").fadeOut(17640);
$("#div5aside").fadeOut(17630);
$("#div6aside").fadeOut(17620);
$("#div7aside").fadeOut(17610);
$("#div8aside").fadeOut(17600);
$("#div9aside").fadeOut(17590);
$("#div10aside").fadeOut(17580);
$("#div11aside").fadeOut(17570);
$("#div12aside").fadeOut(17560);
$("#div13aside").fadeOut(17550);
$("#div14aside").fadeOut(17540);
$("#div15aside").fadeOut(17530);
$("#div16aside").fadeOut(17520);
$("#div17aside").fadeOut(17510);
$("#div18aside").fadeOut(17500);
$("section").fadeOut(0);
});
});
</script>

If I understood your question right, you should do a toggle, I find this the simpliest way to do that:
$(document).ready(function(){
var toggle = 0;
$("button").click(function(){
if (toggle === 0) {
$("#yourDivsToFadeIn").fadeIn(YourTimeToFadeIn);
toggle = 1;
}
else if (toggle === 1) {
$("#yourDivsToFadeOut").fadeOut(YourTimeToFadeOut);
toggle = 0;
}
});
});
EDIT: You also could use:
$(document).ready(function() {
$("button").click(function() {
$("#YourDivsIds").fadeToggle(YourTimeToToggleTheFade);
});
});
But I find the first way to do this better, because if you get to learn some more Javascript/jQuery, there arent always .toggle methods to toggle something. Then you better should learn - and get used to - the first method.
-But thats just my point of the view.

At first you need two buttons in your HTML:
<button id="infader">Fade all in</button>
<button id="outfader">Fade all out</button>
Then in your JS you first select all divs to fade with one jQuery selector and store them in a variable. It's faster, less to write and the attachment of the different fading times becomes easier.
// get all divs with an ID that ends with 'aside'
var asides = $("div[id$='aside']");
// get first button and attach the click-handler
$("#infader").click(function() {
// take all asides and use 'each() to execute a function on each of them
// keyword 'this' is one div-element, i is it's index in the collection
asides.each(function(i) {
// the divs gets a fading time depending on their index
// the first (i == 0) gets 100ms, the last (i == 17) gets 1800ms
$(this).stop().fadeIn((i + 1) * 100);
});
});
// get second button similar
$("#outfader").click(function() {
asides.each(function(i) {
$(this).stop().fadeOut((17 - i) * 10 + 17500);
});
});
What does the .stop() before fade? Lets say you have started a fadeIn and then click the out-button before it has completed. Now the fadeIn ist stopped and the fadeOut begins immediately. If you want instead the fadeIn finishing completely before fadeOut runs just remove the .stop().
Its easy to change the fade-times to fit your needs.

Related

Local Storage, and how to delay div visibility

I am using localstorage to show a div only once, and although the code it works very well, I would like to know how I can delay the visibility of this div ( #alert ) for 1 - 2 seconds (the first time the visitor is shown), and then do a fade in, so that it does not appear suddenly.
My code:
const showMsg = localStorage.getItem('showMsg');
if(showMsg === 'false'){
$('#alert').hide();
}
$('.closebtn').on('click', function(){
$('#alert').fadeOut('slow');
localStorage.setItem('showMsg', 'false');
});
You can run the demo here:
https://jsfiddle.net/0966x2dw/7/
My problem has a solution?
Thanks.
EDIT:
Ops, right. I used CSS Transitions on my #alert div, and now it's much better.
Thanks.
https://jsfiddle.net/0966x2dw/23/
First add "display: none;" to your .alert. Then you can do something like:
if(showMsg === 'false'){
$('.alert').hide();
} else {
$('.alert').delay(1000).fadeIn();
}
This will cause your alert div to bump the content below it down. You may want to use slideDown() instead to make it less abrupt.
(Note that if your alert is critical to your users, you should adjust this to make sure it displays for the small % of people who have Javascript off.)

Refresh div during JQuery update

I have a html file with many div. Beside this I have a JQuery file too which run an AJAX request in every 30 seconds. In my JQuery If a condition met and the jQuery reloded 3 times I want to update my div-s. I tried to add a div, but it does not appear just when I reload my whole page. If I set to remove my div and not add, the JQuery removes my div, so it is very odd for me, because just the .add or .append or .html do not working. furthermore I set a class with invisibility too, and I also set that when the condition met the jQuery file remove the invisibility class, but the div do not want to appear. I am trying to create a sample code.
My html
<div class="row">
<div id="myclass" class= "invisible" >
<div <p> Please appear for me!<p></div>
</div>
</div>
My JQuery:
if (condition) {
$('#myclass').removeClass('invisible');
if (n >= 2) {
$('#myclass').addClass('invisible');
}
}
The main point is, If the conditions met the class not removes just When I reload my page. In the jQuery file the n is equal with the times when the AJAX reloaded with setInterval. My question is why my div not appear just when I reload my whole page? Also why remove without reload?
Thank you in advance the answers!
removeClass and addClass perfectly work. at first, you can check if you jQuery works, just try to write you script (with ".append",".html",".insertAfter") directly in browser console, else you can add some console.log in your code, when you change invisibility like:
console.log('removeClass');
$('#myclass').removeClass('invisible');
if (n >= 2) {
console.log('addClass');
$('#myclass').addClass('invisible');
}
for update some div content, you can use simple function for it. like -
call self page in get request, and replace div content.
function reloadMyDiv(selector){
var element = $(selector);
if(element.length===1){
$.get(window.location.href,{},function(response){
var new_page = $('<div></div>').append(response);
var new_element = new_page.find(selector);
if(new_element.length===1){
element.html( new_element.html() );
console.log('update');
}else{
console.log('need contains only one element, '+new_element.length+' found!');
}
});
}else{
console.log('need contains only one element, '+element.length+' found!')
}
};
and if you more _ not use your interval, is good practice for clear it.
var n = 0;
var myInterval = setInterval(function(){ myFunction() },30*1000);
function myFunction(){
n+=1;
//do, what you want to do
if(n>2){
clearInterval(myInterval);
}
}

FadeIn / FadeOut make DIV's stack instead of overlapping? Using 'absolute' wasn't a solution

I am currently using the the following piece of code to fade in/out various DIV's (which hold information). This works, however I am not satisfied with the result. It should overlap each other, instead of piling up on each other.
I did a search and the only workable thing for me was to add: position:absolute; in the CSS. Though this works, it messes up the rest of the items underneath it. So I am looking to fix this.
I did read about inserting a so-called call-back function, however I don't know how to use that with this coding.
Here is a piece of the fade in/out code:
$('.extraInfo').hide();
$('input').on('ifChecked', function(event){
var extraInformationId = $(this).closest('label')[0].id;
if(extraInformationId != undefined) {
$('div.extraInfo[data-extrainformationfor="' + extraInformationId+'"]').fadeIn(500);
}
});
$('input').on('ifUnchecked', function(event){
var extraInformationId = $(this).closest('label')[0].id;
if(extraInformationId != undefined) {
$('div.extraInfo[data-extrainformationfor="' + extraInformationId+'"]').fadeOut(500);
}
});
The best thing I can come up with myself, other than changing the CSS to absolute, is by changing fade in/out from 500 to 0. However that's not really a solution. :|
If you need more information and/or details, here is the JSFiddle.
When you click on the items, you will notice the DIV's are stacking. This, in my opinion, makes things look kinda 'ugly'.
Remove the ifUnchecked part and use this for the ifChecked
$('input').on('ifChecked', function(event){
$("div.extraInfo")
.fadeOut(500) // hide all divs with class `extraInfo`
.promise() // "wait" for the asynchonous animations to complete
.done(function() { // and then show the info for the selected one
var extraInformationId = $(this).closest('label').attr("id");
if(extraInformationId) {
$('div.extraInfo[data-extrainformationfor="' + extraInformationId+'"]').fadeIn(500);
}
}.bind(this)); // preserve the value of this for the callback of fadeOut
});
fiddle
Don't use fadeout, use hide
$('input').on('ifUnchecked', function(event){
var extraInformationId = $(this).closest('label')[0].id;
if(extraInformationId != undefined) {
$('div.extraInfo[data-extrainformationfor="' + extraInformationId+'"]').hide();
}
});
I made it work by introducing some delay.Since checking & unchecking is happening almost simultaneously you are seeing two text before one get removed
$('input').on('ifChecked', function(event){
var extraInformationId = $(this).closest('label')[0].id;
if(extraInformationId != undefined) {
setTimeout(function(){
$('div.extraInfo[data-extrainformationfor="' + extraInformationId+'"]').fadeIn(1000);
},1000)
}
});
[jsfiddle][1]

How do I transition to the last slide using fadeIn()

I made a script in order to create this "slideshow": http://jsfiddle.net/LWBJG/2/
yet I can not go back to the last slide if I hit "previous" when it is on the first slide
I tried using the last-child selector but had no success
I also tried resetting the count directly like so:
if(count==1){
count=2;
$(".slideshow :nth-child("+count+")").fadeIn();
}
I've been stuck with this for two days, I'm trying to understand what I'm doing wrong!
all I what's left to do is to go to the last slide if I hit "previous" while I'm "standing" on the first slide
First you need to hide all the other .slideshow img elements not being shown when your page first loads. You can do that multiple ways, but here's an example:
$(".slideshow img:not(:nth-child(" + count + "))").hide();
Next, you need to hide the current showing slide when going to the previous one:
$(".slideshow :nth-child(" + count + ")").fadeOut();
Finally, you need to set the count to the number of elements in .slideshow img when going to the last image:
count = $(".slideshow img").length;
Here's a working example: http://jsfiddle.net/LWBJG/22/
You simply were not fading out in the prev loop like you were in the next button loop.
$(".slideshow :nth-child("+count+")").fadeOut()
Also, in the css, i put the following code:
.slideshow > img:not(:first-child) { display:none;}
This makes only the first img appear as default, and then the other ones will fade in as necessary. The way you currently have it, is count is updating properly but your images are inline and are appearing behind the current image number 1.. But on your next loop click, you properly fade out the images.
Hope this helps. Here is the http://jsfiddle.net/LWBJG/18/
Yes i know, i'am late to the party, but I played around a bit. Maybe someone will find the solution useful later on.
Here is a demo: http://jsfiddle.net/NicoO/LWBJG/25/
var $slideContainer = $(".slideshow")
var totalSlides = getAllSlides().length;
var slideIndex = 0;
function getAllSlides(){
return $slideContainer.children("img");
}
function getSlide(index){
return $slideContainer.children().eq(index);
}
function slideExists(index){
return getSlide(index).length;
}
function getCurrentSlide(){
return getSlide(slideIndex);
}
function animateSlide(){
getAllSlides().fadeOut();
getCurrentSlide().fadeIn();
}
$("#next").on("click", function () {
slideIndex++;
if(!slideExists(slideIndex))
slideIndex = 0;
animateSlide();
});
$("#prev").on("click", function () {
slideIndex--;
if(!slideExists(slideIndex))
slideIndex = totalSlides-1;
animateSlide();
});
Using multiple fadeIn()s might lead to a mess. In your case, if you really want to do so, you can first fadeOut() all images before fadeIn() the desired one. This solves the problem.
$(".slideshow img").fadeOut();
$(".slideshow :nth-child("+count+")").fadeIn();
hide() should also work.

jQuery to slide a div right to left slides the div out of window

I have created a slider that slides from right to left. I am changing margin-right to make the slide work.
As per the requirement, I have a treeview, when user clicks on any node, it opens a sliding dialog with some controls in it. When user clicks on any node, it should first close the previously open dialog and then open the dialog for currently selected node. I am able to make this work when user clicks on the node, the dialog opens, and when user click back again on the same node or the slider-button, the dialog hides. But somehow, the code to hide when user click on any other node doesn't work properly. It moves the slider-button and the dialog away and I don't see anything.
I used the following code:
if($('#slider-button').css("margin-right") == "400px") {
$(sliderDialog).animate({"margin-right": '-=400'});
$('#slider-button').animate({"margin-right": '-=400'});
} else{
$(sliderDialog).animate({"margin-right": '+=400'});
$('#slider-button').animate({"margin-right": '+=400'});
}
I thought, it as simple as finding if the previously selected dialog is different than current than just call the same code that hides the dialog when user clicks on the same node again. ie.
$(sliderDialog).animate({"margin-right": '-=400'});
$('#slider-button').animate({"margin-right": '-=400'});
But, it behaves weird. Anyone, what am I missing here?
Here is my jsFiddle.
Using the DOM and such that you had, I've updated the JS to switch between them after animating back (here is the Fiddle in action):
var sliderDialog = "#dvPriorityDialog"
function slideIt() {
var sliderId = '#' + $('.pollSlider.open').attr('id');
var slideWidth;
if ($('.pollSlider').hasClass('open')) {
slideWidth = $('.pollSlider.open').width();
$('.pollSlider.open').animate({"margin-right": '-=' + slideWidth}, function() {
if (sliderId != sliderDialog) {
slideIt();
}
});
$('#slider-button').animate({"margin-right": '-=' + slideWidth});
$('.pollSlider.open').removeClass('open');
} else {
slideWidth = $(sliderDialog).width();
$(sliderDialog).addClass('open');
$('#slider-button').animate({"margin-right": '+=' + slideWidth});
$(sliderDialog).animate({"margin-right": '+=' + slideWidth});
}
}
function bindControls() {
$('#slider-button').click(function() {
slideIt();
});
$("#liPriority").click(function() {
sliderDialog = "#dvPriorityDialog";
slideIt();
});
$("#liFasting").click(function() {
sliderDialog = "#dvFastingDialog";
slideIt();
});
}
// init;
$(document).ready(function() {
bindControls();
});
Try
$(sliderDialog).stop().animate({"margin-right": '-=400'});
$('#slider-button').stop().animate({"margin-right": '-=400'});
You have multiple problems :
You try to move a same element (#slider-button) in function of two different animations (a panel go left and an other go right). To resolve that, the best option is to add a button to each panel. It will be a lot easier to manage global behavior because you have only one animation by panel.
You don't stop animation when you want to change them. Store your animation in vars and use .stop() function with the first param to true in you case (.stop(true) to stop animation and remove it from queue without finish it).
Your state test is based on your animated css attribute (margin-right). So you alltime have to wait the end of animation to start the new one. To fix that use vars to store your animations state : (var firstPanelLastMove = 'left' // or right ... etc).

Categories

Resources