Best/proper way to fade-in-out changing html text? - javascript

I am creating a sample website for practice and I created a function that changes the main background image of the site every x amount of seconds. Along with the changes to the background-image, I would like to change the title text that corresponds to each image. I can fade-in-out the background-image nicely, but the text cannot fade.
I'm assuming its because I am not changing the css but because I'm changing the html text directly so transition doesn't work.
Here is my function:
function updateImage() {
if (pic == 1) {
caption = "GO BEYOND EARTH";
}
else if (pic == 2) {
caption = "EXPLORE NEW WORLDS";
}
else if (pic == 3) {
caption = "EXPERIENCE DEEP SPACE";
}
$('.pic-titles').text(caption);
$('.center').css('background-image', 'url(img/space' + pic + '.jpg');
pic++;
if (pic > 3) {
pic = 1;
}
}
});
Right now the text just changes and it doesn't look that great. I want it to match the fade effect of the background image. I tried using jQuery fadeIn and fadeOut together but the outcome doesn't look too great.

You need two things, the animate method and the queue. With this combo youll be able to fadeout the text on the first animate, change the text right at that point. And at last fadein the new text.
Hope this is what you were looking for. Happy to explain or help in a better solution if needed.
var pic = 2;
function updateImage() {
if (pic == 1) {
caption = "GO BEYOND EARTH";
} else if (pic == 2) {
caption = "EXPLORE NEW WORLDS";
} else if (pic == 3) {
caption = "EXPERIENCE DEEP SPACE";
}
//Animate function
$('.pic-titles').animate({
opacity: 0
})
.queue(function() {
$(this).text(caption);
$(this).dequeue();
})
.animate({
opacity: 1
});
//$('.center').css('background-image', 'url(img/space' + pic + '.jpg');
pic++;
if (pic > 3) {
pic = 1;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="pic-titles">GO BEYOND EARTH</p>
<button onclick="updateImage()">PIC</button>

Related

How can I change body background color depending on active slide?

I am using Swiper (no jQuery, pure JavaScript) to display 11 slides. I want to change the body background-color depending on which slide the user is on.
This code works fine, but when the slider restarts it keeps the colour of the last slide instead of restarting from the first one:
swiper.on('transitionEnd', function(e) {
if (this.activeIndex == 1) {
document.querySelector("body").style.background = '#F4F1C1';
}
if (this.activeIndex == 2) {
document.querySelector("body").style.background = '#DCDDDE';
}
if (this.activeIndex == 3) {
document.querySelector("body").style.background = '#ECEBDF';
}
if (this.activeIndex == 4) {
document.querySelector("body").style.background = '#F2E3E3';
}
if (this.activeIndex == 5) {
document.querySelector("body").style.background = '#D0EFF0';
}
});
On this JSFiddle you can see that after slide 11, the slider goes back to slide 1 but the colour is still #999999 rather than #F4F1C1.
Why is the index not restarting?
Swiper shifts its array index by 1. As seen here in the documentation
So you're correctly starting from index 1 but not accounting for the 11th item at index 12
https://swiperjs.com/api/
You can use this.realIndex to get the correct index of the looped item according to the documentation.

Using js verification to change background-image

i'm with a little problem. I was building a form in HTML with javascript, but in the inputs, i've used a background-image and a padding in left to make it look better, here its all ok, the problem comes next. I've created this function here:
function verificar_email(email) {
var valor = email.value;
if (valor.length != 0){
if (valor.indexOf('#') >= 1) {
if (valor.indexOf('.') > (valor.indexOf('#') + 1)) {
if (valor.length > (valor.lastIndexOf('.') + 1)) {
email.style.background = "#1abc9c";
email.style.color = "#fefefe";
return true;
}
}
}
}
email.style.background = "#ff0000";
email.style.color = "#fefefe";
return false;
}
When the email input is blank or typed wrong, it's filling my bgimage with bgcolor and making the image dissapear. How can i change my original image to other image i've created without filling with color?
Sorry for my bad english, below i will explain what i'm talking about with some images.
http://imgur.com/a/hkigg - the first image is the error, the second is what it looks like and the final image is what i wanna do.
you can simply set the background color to "transparent" which should stop your background image disappearing

Clearing styles once attempt is made

In my spelling game the user clicks on the letters to make them animate in to the slots on the grid to spell the words.
I have designed it so when a word is spelt correctly, a style is applied called "wordglow2" that makes the word disappear and reveal the picture behind - which is the aim of the game.
When the user gets the word wrong the he/she is given a second attempt at the word. When the user gets the word wrong a style called "wordglow4" is applied to the word which makes it glow red. The problem is the style applied to wrong words does not go away to clear the space for another attempt.
How do I make the styles dissapear 2 seconds after the 3rd letter of the word is clicked (attempt is made)?
This code applies the styles depending on whether the word is right or wrong...
if (!$('.drop-box.spellword:not(.occupied)').length) {
var wordIsCorrect = 0;
$('.drop-box.spellword').each(function() {
if ($(this).attr("data-letter") == $(this).find("div").attr("data-letter")) {
wordIsCorrect++;
}
});
console.log(wordIsCorrect);
console.log($('.drop-box.spellword').length);
if ($('.drop-box.spellword').length == wordIsCorrect) {
$('.drop-box.spellword').addClass('wordglow2');
$(right).val('Well Done!');
$(right).show();
audioS.play();
$('.counter').html(completeWords + '/6').show();
$(wrong).hide();
$('.minibutton').prop('disabled', false);
} else {
$('.drop-box.spellword').addClass("wordglow4").css('color', 'transparent');
$(wrong).val('Try Again');
$('.minibutton').prop('disabled');
$(wrong).show();
audioF.play();
$('.counter').html(completeWords + '/6').show();
$(right).hide();
$('.minibutton').prop('disabled', true);
}
}
});
}
var completeLetters = $('.wordglow2').length;
var completeWords = (completeLetters / 3);
$('.counter').html(completeWords + '/6');
if (completeWords == 3) {
$('table').fadeOut(2000);
}
var incompleteWords = $('.spellword').hasClass('.wordglow4').length;
if (incompleteWords == 3) {
$('.minibutton').prop('disabled', false);
}
});
I have tried this...
if $('.drop-box.spellword').hasClass("wordglow4") {
$("wordglow4").fadeOut(2000);
}
Here is a working fiddle... http://jsfiddle.net/smilburn/3qaGK/25/
I don't understand quite what you want to do, but something like this might cut it:
$('.drop-box.spellword')
.animate({ 'opacity': 1 }, 2000, function()
{
$(this)
.removeClass('wordglow4')
.removeClass('occupied')
.html('')
});
http://jsfiddle.net/cTGGA/
User the removeClass method to do that. You can put a duration/animation on the removeClass call itself:
$('.drop-box.spellword').removeClass("wordglow4", "2000");
This removes the class and animates the transition, probably what you are looking for.

Animate a percentage positioned DIV in JavaScript

I decided to improve my JavaScript skills by practicing with some often used modules.
I am creating a fixed feedback button that comes up when you press it and goes down when you press again. Everything works, but I want it to be animated.
I used this code to get it done
function rollUp(item){
if(item.className == "on") {
item.className="off";
document.getElementById("container").style.top = "97%";
} else {
item.className="on";
document.getElementById("container").style.top = "78.5%";
}
}
Now I just don't get those percentages animated, I found many descriptions about animating divs by px, but I don't get this working.
So the div has to be moved from top position 97% to 78.5%
Any help?
Are you using jQuery? If yea, please try this:
function rollUp(item){
if(item.className == "on") {
item.className="off";
$("#container").animate({top: "97%"});
} else {
item.className="on";
$("#container").animate({top: "78.5%"});
}
}
You would need something like a timeout which will change the position in small steps which actually is "animation", here
function rollUp(){
var ph=document.getElementById("container").style.top.toString();
ph.replace("px","");
var phi=parseInt(ph);
if(phi<800){
if(item.className == "on") {
item.className="off";
document.getElementById("container").style.top = (phi+10).toString()+"px";
} else {
item.className="on";
document.getElementById("container").style.top = "600px";
}
Window.setTimeout(roolUp(), 300);
}
}

Multiple Image fadeIn onLoad (at the same time)

I want to fade in multiple images at the same time as the page loads. Just like this website does it: http://www.struckaxiom.com/work. I have the script to do it only on one image, but I want to have more images included.
This is the single photo script. Please help.
document.write("<style type='text/css'>#thephoto {visibility:hidden;}</style>");
function initImage() {
imageId = 'thephoto'
image = document.getElementById(imageId);
setOpacity(image, 0);
image.style.visibility = "visible";
fadeIn(imageId,ImageId2,0);
}
function fadeIn(objId, opacity) {
if (document.getElementById) {
obj = document.getElementById(objId);
if (opacity <= 100) {
setOpacity(obj, opacity);
opacity += 10;
window.setTimeout("fadeIn('"+objId+"',"+opacity+")", 100);
}
}
}
function setOpacity(obj, opacity) {
opacity = (opacity == 100)?99.999:opacity;
// IE/Win
obj.style.filter = "alpha(opacity:"+opacity+")";
// Safari<1.2, Konqueror
obj.style.KHTMLOpacity = opacity/100;
// Older Mozilla and Firefox
obj.style.MozOpacity = opacity/100;
// Safari 1.2, newer Firefox and Mozilla, CSS3
obj.style.opacity = opacity/100;
}
window.onload = function() {initImage()}
// -->
</script>
Thanks!
Simple array and loop are all you need.
First, add such array on top of the code:
var images = [ "thephoto1", "thephoto2", "thephoto3" ];
(With the ID of all desired images)
Next change the function name to initImages to reflect the fact it will initialize more than one image and finally add that loop:
function initImages() {
for (var i = 0; i < images.length; i++) {
imageId = images[i];
image = document.getElementById(imageId);
setOpacity(image, 0);
image.style.visibility = "visible";
fadeIn(imageId, 0);
}
}
That's it, no need to touch the other functions.
Live test case with cute cats: http://jsfiddle.net/yahavbr/e863X/ :-)
You could just wrap all of your images in a single container like this:
<div id="imageContainer">
<img src="img1.jpg">
<img src="img2.jpg">
<img src="img2.jpg">
</div>
Change your CSS to this:
<style type='text/css'>#imageContainer {visibility:hidden;}</style>
Change your first function to this:
function initImage() {
containerId = 'imageContainer'
container = document.getElementById(containerId);
setOpacity(container, 0);
container.style.visibility = "visible";
fadeIn(containerId,0);
}
By running the fading effect on the container you can then add as much content to the container and it will all fade in together and you never have to update your code.
The way they are doing is using jQuery (an excellent implementation). All of the images are in the same container and are selected using the jQuery class selector. Then they fade in all elements that fit within the viewable area. Their js file is not minimized so you could reverse engineer most of that functionality. The important thing to note is not that it is showing each row at a time but every element that fits in the viewing area. Their key function looks like this:
var elTop = $(el).offset().top - $(window).scrollTop();
var elHeight = $(el).height();
// if between top of footer and top of window
if (elTop + elHeight > 40 && elTop < $(window).height()) {
if ($.inArray($(el).attr("data-unique-id"), elementsInView) < 0) {
addToView(el);
}
} else {
if ($.inArray($(el).attr("data-unique-id"), elementsInView) >= 0) {
removeFromView(el);
}
}
addToView and removeFromView add and remove the element from an array, then fade is executed on the array.

Categories