change background image on click with jquery and html5 - javascript

How can I do to change background image onClick with jquery or java script?
For Example: I have Six(6) images and I want change to NEXT background image when i click on ">" (next arrow) and change to previous background image when I click on "<" (back arrow).
I'm developing this website with responsive html5 and css3.
<script type="text/javascript" src="jquery-1.8.2.min.js"></script> //jquery inside the folder ok
<script type="text/javascript">
var images = ['url("../images/1366x768/image-_0107.jpg")', 'url("../images/1366x768/image-_0012.jpg")'], curIndex = 0; // here I set the images inside the desired folder
// Left arrow selector
$('.backarrow').click(function () { //here I set the back arrow "<"
if (curIndex > 0) {
// Container selector
$('backgrounds').css('../images/1366x768/image-0061.jpg', images[--curIndex]); // here I set my file backgrounds.css and the default image configured there
}
});
// Right arrow selector
$('.nextarrow').click(function () {
if (curIndex < images.length - 1) {
// Container selector
$('backgrounds').css('../images/1366x768/image-0061.jpg', images[++curIndex]);
}
});
</script>
<!--HTML 5 -->
<div id="square">> <!-- here I call my jquery -->
</div>
<div id="square">< <!-- here I call my jquery -->
</div>
/* CSS3 */
/* backgrounds.css */
body {
background: #dcd8d5 url(../images/1366x768/image-_0061.jpg) no-repeat center center fixed; -webkit-background-size: cover;
-moz-background-size: cover; -o-background-size: cover; background-size: cover }
/* default.css */
.nextarrow {
font-size:20px; color:#666; font-style:normal
}
.backarrow {
font-size:20px; color:#666; font-style:normal
}
WHAT I'M DOING WRONG?

The jQuery approach for this is below:
$("#background").css("background-image","url(img_url_here)");
I'm not entirely sure what you are trying to select so I made a jsfiddle which will hopefully make it easier for you to figure out:
JSFiddle

The error seems to be in this line:
$('backgrounds')
What exactly are you trying to select with this? If is an object with id = "backgrounds" you should use $('#backgrounds'), if it's a class you can select it by using $('.backgrounds'). The way you are using, jQuery is trying to search for an element (i.e. tag) named "backgrounds". (Which I'm pretty sure is not what you are trying to do)
Any way, in case you want to change the background-image from, let's say, your body element you should use something like:
$(document).ready(function() {
$(".nextarrow").click(function(){
{
$('body').css("background-image","url(../images/1366x768/image-0061.jpg)"); // Correct the path to your image
}
}
Alternatively, you can change the background-image from an element which id happens to be "backgrounds" using:
$('#backgrounds').css("background-image","url(../images/1366x768/image-0061.jpg)"); // Correct the path relative to the html document this script is running.
I hope it helped. Cheers

Related

Play animation when content get into view

I've been searching on many posts but almost all of them are confusing.
I'm working with animate.css into a which is at the middle of my page.
For default the animation is played when the page is loaded, but i want that it play when i reach the (when i'm scrolling).
Please, don't say about JS Reveal, i'd like to use the animation from animate.css
What i was trying:
HTML
<!-- Others div above -->
<div class="row sf-medida" id="sf-medida" onscroll="Animar();">
<!-- Others div below -->
JS
function Animar() {
setTimeout(function(){
document.getElementById("sf-medida").style.visibility = "visible";
$("#titulo-general").addClass("animated fadeInLeft");
$(".sub-titulo").addClass("animated bounceInRight");
$(".titulo-izquierda").addClass("animated swing");
$(".texto-1").addClass("animated fadeIn");
$(".texto-2").addClass("animated fadeIn");
},1000)
}
But it doesn't work, however, i've tried adding
window.addEventListener("scroll", Animar);
But what it does is that the animation is played whenever i scroll on the page,
This can be very easily done using little jquery. All you need to do is listen to the scroll event, then check if user have scrolled to the target element. If the user did, then add animation class from your animate.css. Adjust your if condition according to your desires. Check the below code and fiddle https://jsfiddle.net/15z6x5ko/ for reference
$(document).ready(function(){
$(document).scroll(function(evt){
var v2 = Math.abs($('.box').position().top - $(window).height()/2);
var v1 = $(this).scrollTop();
if( v1 > v2 ){
console.log('in');
$('.box').addClass('animated flip')
}
});
});
So as per your request, let me try to explain the code line by line
$(document).ready(function(){
This is easy to understand. It just waits for browser to load all HTML & CSS first and when everything is loaded, the javascript code inside this function will run.
$(document).scroll(function(evt){
This is an event handler, our callback function will run whenever user scrolls on document. Remember change $(document) according whatever the parent is of your target element. So if your target div is inside another div whose class is .parent then use $('.parent').scroll . As for my code I am listening the event on document. When my document scrolls, my event will trigger.
var v1 = $(this).scrollTop();
This code will get the amount of scrolling user had done in pixels.
var v2 = Math.abs($('.box').position().top - $(window).height()/2);
This is a simple math that checks the position of my target div from its parent element subtracting the half of the size of window from it. This will return the pixel positing of your target div. So when user reaches this pixel positing while scrolling, your animation will start.
$('.box').addClass('animated flip')
Now this code simply adds the animation css classes into the target div as soon as user scrolls to the target div.
I'm using "WoW.js" for my scroll reveal library. It's pretty easy to use, like for real. One line of code
<div class="wow fadeIn">content</div>
Here, take a look: http://mynameismatthieu.com/WOW/docs.html
Here's an example using Jquery.
In it we use .scrollTop and .height to measure the videos container from the top of the page so that we know when it comes into view when scrolling. (it's actually set to load when it reaches 100px below the bottom of the viewable area, a sort of preload. you can adjust it to whatever you like.)
The video load is done by copying the url from data-src= into src= when the video container is at the desired spot on the page. (in this case, 100px below the viewable area)
fiddle
note, the video won't load on stack so be sure to view the fiddle
https://jsfiddle.net/Hastig/xszu6b1p/
I scraped it together from these two answers..
Youtube Autoplay
Ladyload Images
$(window).scroll(function() {
$.each($('iframe'), function() {
if ( $(this).attr('data-src') && $(this).offset().top < ($(window).scrollTop() + $(window).height() + 100) ) {
var source = $(this).data('src');
$(this).attr('src', source);
$(this).removeAttr('data-src');
}
})
})
body {
margin: 0;
}
.filler {
display: flex;
justify-content: center;
align-items: center;
height: 800px;
}
.filler-top { background-color: blue }
.filler-btm { background-color: green; }
.video-container {
/* css tricks - responsive iframe video */
/* https://css-tricks.com/NetMag/FluidWidthVideo/Article-FluidWidthVideo.php */
position: relative;
padding-bottom: 56.25%; /* 16:9 */
padding-top: 25px;
height: 0;
display: flex;
justify-content: center;
background-color: red;
}
.video-container iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="filler filler-top">filler top</div>
<div class="video-container">
<iframe data-src="https://www.youtube.com/embed/f0JDs4FY8cQ?rel=0&autoplay=1"></iframe>
</div>
<div class="filler filler-btm">filler bottom</div>

JQuery, not animating my background image when trying to refresh

I'm talking about this site here: malcolmtanti.com
I am using this function:
<script>
var image = new Image();
image.onload = function () {
$('header').animate({opacity: 1}, 2000);
}
image.src = "./images/background.jpg";
</script>
to animate the fade in of my main background image and the title etc. It should fade in the header element in my css.
This is the CSS:
header{
position: relative;
background: url(../images/background.jpg) no-repeat top center;
background-size: cover !important;
-webkit-background-size: cover !important;
/*height: 700*/
top:50px;
min-height:95%;
max-width: 100%;
overflow: hidden;
opacity:0;
}
For some reason, the first time I access the site, the picture loads for me, but once I press refresh, the opacity of the header tag is remaining 0. How can this be?
It might be a problem with the browser caching the image so that when you refresh the page it doesn't fire the animation since the image is already preloaded.
Try loading the image with a unique id (like the current time) to prevent this.
<script>
var image = $('<img/>');
var srcText = './images/background.jpg?t=' + new Date().getTime();
image.attr('src', srcText).load(function() {
$(this).remove();
$('header').animate({opacity: 1}, 2000);
});
</script>
U have used the link from (link tag, script tag )the href = "http://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css" and src of the script like this. Don't use like this. copy the code of above link and place it in your folder and refer that local link..

click to change background toggle

When I click on it changes background. It works fine. But what if I want to click on it again to restore the original background? I have this code:
jQuery(document).ready(function($) {
$(".select").on("click", function () {
$(this).css("background-image", "url(images/selected.png)");
});
});
Here is jsfiddle EXAMPLE
Basically when I click on the div it changes the background, which is fine. But I want to have ability to click on it again to restore the original background.
It will be an alternative solution for tick box, but just for demo purposes.
Thanks
JS
replace
$(this).css("background-image", "url(images/selected.png)");
with
$(this).toggleClass("active");
Style
#multiselect .active {
background-image: url('...');
}
Fiddle http://jsfiddle.net/09xgrhxo/4/
Instead of using .css() to change the background-image I would add a class in your CSS and use .toggleClass().
Also be aware that simply adding a class will not be specific enough because your css is using:
#multiselect .select
you're going to have to target the class you add as a child of #multiselect:
#multiselect .change
CSS
#multiselect .change{
background-image: url(http://t2.gstatic.com/images?q=tbn:ANd9GcSZ51HqKXkejWAFcSBrodHd5eUN2QaIJro0jhN1YpmljSdQ5dj2)
}
JS
$(".select").on("click", function () {
$(this).toggleClass("change");
});
FIDDLE
You could use data-* attribute.
$('.select').attr('data-img', $('.select').css('background-image'));
$(".select").on("click", function() {
$(this).css("background-image", ($(this).css('background-image') == $(this).data('img')) ? "url(http://t2.gstatic.com/images?q=tbn:ANd9GcSZ51HqKXkejWAFcSBrodHd5eUN2QaIJro0jhN1YpmljSdQ5dj2)" : $(this).data('img'));
});
#multiselect .select {
background: url(http://t0.gstatic.com/images?q=tbn:ANd9GcQF_ErOlc78eOGZaEWb-dwPkrv2uyAoKx0Pbn3-e0tAZoUDSQRCsA) center;
width: 250px;
height: 100px;
margin-bottom: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="multiselect">
<div class="select">Option1</div>
<div class="select">Option2</div>
<div class="select">Option3</div>
</div>
Instead of writing background-img url in javascrpt, I would suggest to create two classes having same properties but different background-img url which you want to toggle. so here we will be toggling class (ultimately background-img) in javascript.
see jsfiddle [example][1]
[1]: http://jsfiddle.net/09xgrhxo/13/

Toggle div on div click horizontally

I made a div which has a background image of a face, I have designed div which contains a paragraph, 2 buttons and an input box.
I know this question has been asked quite often however my situation is different, I'd like for my div with the background image of a face to be clickable so that the div containing everything else slides out from the left.
What is the best method to do this?
HTML
<div id="image"></div>
<div id="container">
<p>I like nutella and croissants</p>
<input id="message" placeholder="type...." required="required" autofocus>
<button type="button" id="send">Send</button>
<button type="button" id="close">Close</button>
</div>
CSS
div#image { background: url(http://i.imgur.com/PF2qPYL.png) no-repeat; }
JQUERY
$(document).ready(function(){
$( "#image" ).click(function() {
jQuery(this).find("#container").toggle();
});
});
Using the article link posted by Raimov (which I actually came across in a Google search before realize he posted it as well ;), we can use jQuery to animate the width when the toggling element is clicked. Remember that a background does not add size to an element, so the toggle with the background image must have a height attribute set. Also, if you have long lines of text in the form, you'll have to wrap them yourself or use another method from the article.
http://jsfiddle.net/iansan5653/wp23wrem/ is a demo, and here is the code:
$(document).ready(function () {
$("#image").click(function () {
$("#container").animate({width: 'toggle'});
});
});
and this CSS is necessary:
div#image {
background: url(http://i.imgur.com/PF2qPYL.png) no-repeat;
height: 36px;
/*height needed to actually show the div (default width is 100%)*/
}
#container {
white-space: nowrap;
overflow: hidden;
}
I created a jsFiddle for you, where after clicking on img, the form hides to the left.
$("#image").click(function() {
var $lefty = $(this).children(); //get the #container you want to hide
$lefty.animate({
left: parseInt($lefty.css('left'),10) == 0 ?
-$lefty.outerWidth() : 0
});
The resource was taken from:
Tutorial how to slide elements in different directions.

Background Image Carousel

I'm trying to create a simple website that only consists of background images inside a carousel that will move from left to right, with directional arrows. I have found one resources that provides a simple example however when I tried to reproduce their model, the script doesn't seem to define itself. Also, there is the second issue with actually making it full-screen since the demo is only 700x500.
Here is a link to the resource: Dynamic Drive.
Also, here is my HTML
<!DOCTYPE html>
<head>
<title>Hit Heavy</title>
<link rel="shortcut icon" href="favicon.ico" type="image/ico" />
<style type="text/css">
div.bgcarousel { /* CSS for main carousel container */
background: black center center no-repeat;
width: 100%;
}
img.navbutton { /* CSS for the nav buttons */
margin: 5px;
opacity: 0.7;
}
div.slide{ /* CSS for each image's DIV container within main container */
background-color: black;
background-position: center center; /* center image within carousel */
background-repeat: no-repeat;
background-size: cover; /* CSS3 property to scale image within container? "cover" or "contain" */
color: black;
}
</style>
<script src="js/jquery-1.8.2.min.js"></script>
<script src="js/bgcarousel.js" script type="text/javascript"></script>
<script type="text/javascript">
var firstbgcarousel=new bgCarousel({
wrapperid: 'mybgcarousel', //ID of blank DIV on page to house carousel
imagearray: [
['bg.jpg'], //["image_path", "optional description"]
['bg.jpg'],
['bg.jpg'],
['bg.jpg'] //<--no trailing comma after very last image element!
],
displaymode: {type:'manual', pause:3000, cycles:2, stoponclick:false, pauseonmouseover:true},
navbuttons: ['left.png', 'right.png'], // path to nav images
activeslideclass: 'selectedslide', // CSS class that gets added to currently shown DIV slide
orientation: 'h', //Valid values: "h" or "v"
persist: true, //remember last viewed slide and recall within same session?
slideduration: 500 //transition duration (milliseconds)
})
</script>
</head>
<body>
<div id="mybgcarousel" class="bgcarousel"></div>
</body>
</html>
As for the javascript that backs the scripting within the html, you can view it here
The problem is in the following line you have set the width to 100%
div.bgcarousel{ /* CSS for main carousel container */
background: black ;
width:700px; /* default dimensions of carousel */
height:500px;
}
#user2122160 Height is Important change the css like this
div.bgcarousel { /* CSS for main carousel container */
background: black center center no-repeat;
width: 100%;
height:100%;
}
i created Slider based Your Code its Working Well without Error Link below:
http://www.fileconvoy.com/dfl.php?id=g7d74fb2c3b904c6a99923428881a8f81443981afd
I think you need to add a $(document).ready() handler around that code, I think it's running BEFORE jquery and bgcarousel gets loaded, change the script to
<script type="text/javascript">
$(document).ready(function(){
var firstbgcarousel=new bgCarousel({
wrapperid: 'mybgcarousel', //ID of blank DIV on page to house carousel
imagearray: [
['bg.jpg'], //["image_path", "optional description"]
['bg.jpg'],
['bg.jpg'],
['bg.jpg'] //<--no trailing comma after very last image element!
],
displaymode: {type:'manual', pause:3000, cycles:2, stoponclick:false, pauseonmouseover:true},
navbuttons: ['left.png', 'right.png'], // path to nav images
activeslideclass: 'selectedslide', // CSS class that gets added to currently shown DIV slide
orientation: 'h', //Valid values: "h" or "v"
persist: true, //remember last viewed slide and recall within same session?
slideduration: 500 //transition duration (milliseconds)
})
})
</script>
the $(document).ready part makes your code wait for the document to be loaded before executing your script

Categories