Scalable background images that change on click - javascript

I have a question that's somewhat of an extension of this thread.
I have my background images working; however, instead of having them tile automatically, I would like to link them to scale to the browser. I know how to create a scalable background image using CSS, but I don't know how to link said CSS to the backImage variable in the script (available below, or after the jump from the previous thread) so that it applies to all of the various images.
<script type="text/javascript">
var backImage = [
"images/street.png",
"images/market.jpg",
"images/building.jpg",
"images/skyscraper.jpg",
"images/gasstation.jpg",
"images/trees.jpg"
];
function changeBGImage(whichImage) {
if (document.body){
document.body.style.backgroundImage = 'url('+backImage[whichImage]+')';
}
};
</script>
The tricky part is I can't apply the class to the HTML because I'm already applying this...
Change
...to an existing div in the HTML with multiple other classes; hence I need to add the class to backImage or the specific pngs and jpgs in the javascript.
Thanks in advance!

A friend helped me solve my problem. Here goes:
<script type="text/javascript">
var backImage = [
"images/vintagemap.png",
"images/earbuds.jpg",
"images/flames.jpg",
"images/grass.jpg",
"images/library.jpg",
"images/shapes.jpg"
];
function changeBGImage(whichImage) {
if (document.body){
document.body.style.backgroundImage = 'url('+backImage[whichImage]+')';
document.body.className = 'bgchange';
}
};
</script>
I added the line "document.body.className = 'bgchange';" below my original JS, then wrote the following CSS class:
.bgchange {
background-repeat:no-repeat;
background-size:cover;
}
It will now resize any photo to a scalable, full-screen background image.
Hopefully someone else finds this helpful!

as part of your changeBGImage() function, you could make additional .style. changes to document.body to do whatever you like to each background image as it changes.
EDIT:
Essentially, take this:
function changeBGImage(whichImage) {
if (document.body){
document.body.style.backgroundImage = 'url('+backImage[whichImage]+')';
}
};
And turn it into this:
function changeBGImage(whichImage) {
if (document.body){
document.body.style.backgroundImage = 'url('+backImage[whichImage]+')';
document.body.style.backgroundSize = '###px';
}
};
Or, if you want to set some CSS other than background-size on the body element, you would do that after the .style. parameter instead. Just remember, when translating CSS to JS, hyphens are removed and the next letter is capitalized (just like background-image in CSS becomes backgroundImage in JS)

Related

Smooth way to replace background-image

I’m quite new to jQuery and JS and been asked to write a script that will be loading background-image progressively - I mean that low quality image should appear immediately and when full size image is loaded should replace the small one.
I found some tips how to do something similar by layering <img /> on top of background-image however in my case i have to deal with background-image only, so I have made this:
$('.img-loader').each(function(){
var box = this;
var smallImg = $(this).attr('style');
var bigImg = smallImg.replace('.jpg)', 'big.jpg)');
var imgUrl = bigImg.replace('background-image: url', '');
var imgUrlS = imgUrl.replace(/[{()}]/g, '');
console.log(imgUrlS);
$('<img/>').attr('src', imgUrlS).load(function(){
$(this).remove();
$(box).attr('style', bigImg);
});
})
The script basically does the job but in that moment when the image gets replaced there is a quite noticeable ‘shake’.
Any ideas how to make transition smoother or anyone knows what causing this 'shake'?
Edit: As suggested I'm adding a markup snipped of where script has to be applied.
<div class="about__section__bgimage img-loader"
style="background-image: url(<?php echo $contentBlock->imageurl ?>)"></div>
I suggest you create two separate elements with the same size, overlapping each other, with position: absolute; make one of them visible with the original bg image (using opacity: 1). The second one invisible (using opacity:0)
Once the higher quality image is completely loaded, set the opacity of the original image to 0 and the new image to 1.
use a css transition on the opacity property to make the opacities change smoothly.
you have to use animation for this. Use any of them according to your scenario enjoy it !!!
https://daneden.github.io/animate.css/

How to apply blur effect to background image in Blogger?

I've been trying to add blur effect to my posts but only thing that gets blurred is the main post content (pic: http://i.gyazo.com/9d94d2be5dc3f3ada982564aa212336e.jpg). Any idea how to target the background-image, instead of the content?
The code I am using at the moment is:
<script type="text/javascript">
var image = document.querySelector('.post-body img').src;
var target = document.body;
target.style.backgroundImage = "url(" + image + ")";
target.style.backgroundSize = "cover";
document.body.style["background-attachment"] = "fixed";
</script>
I have a odd feeling that you need to make the actual background image into standalone element but I have no idea how.
Also, is there a possibility I could add Blur.js into blogger or is it only for Wordpress? If yes, I'd like to know how?
Thanks in advance.
I worked on this and saw this question. So here's a suggestion.
<script type="text/javascript">
function showBackground() {
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.backgroundImage = "url('http://backgroundImage.jpg')";
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.backgroundPosition = "center center";
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.backgroundRepeat = "no-repeat";
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.backgroundAttachment = "fixed";
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.webkitFilter = "blur(5px)";
}
window.onload = showBackground();
</script>
Explanation
As I used the simple template at this time, I noticed that the standard template has a class named body-fauxcolumn-outer which is used to set the background color.
So I adapt my answer here to answer this question.
I just added the following to fix the blur as you can see in the image bellow.
document.getElementsByClassName('body-fauxcolumn-outer')[0].style.webkitFilter = "blur(15px)";
You could try use this CSS 3 tag:
filter: blur(5px);
You can see the mdn documentation here: https://developer.mozilla.org/en-US/docs/Web/CSS/filter
You can do this on Blogger without using any JS or CSS.
Upload your image into a Blogger post as if you want to put it in an article.
Copy the URL of the image and paste it into the body css like so:
body {
background-image: url('YOUR IMAGE URL HERE');
}
Replace the /s-1600/ part of the url with /s1600-fcrop64=1,000f0000ffceffff:Soften=1,20,0/
Note: You can adjust the radius of the blur by fiddling with the second number after Soften=(in the case above, 20).
The advantage of doing this is it's lighter on code and completely compatible with every device and browser that is capable of loading an image!

CSS Styling inside JS Function

I have the following HTML and Javascript code. The Randomize() function as displayed on the bottom is contained inside of a div which has a certain themeing applied to it.
div id="themeing">
<script type="text/javascript">Randomize()</script>
</div>
function Randomize() {
var images = new Array("images/banner/banner1.jpg","images/banner/banner2.jpg","images/banner/banner3.jpg","images/banner/banner4.jpg");
var imageNum = Math.floor(Math.random() * images.length);
document.getElementById("header").style.backgroundImage = "url('" + images[imageNum] + "')";
}
window.onload = Randomize;
This function would allow me to rotate images in the banner of my website on pageload.
Right now the function works, but the styling, which is applied by CSS to the id="themeing" does not apply to the images which are being output by Javascript.
How do I make it so that the output of Randomize() gets styled appropriately?
I am not sure about the CHTML id you are talking about but the images can be set to cover the whole background by setting two more attributes :
background-repeat: no-repeat; //in case you don't want repetition of image.
background-size: cover;
Hope it helps.
I looked at the same problem yesterday :)
I found the solution using Jquery plugin and the .css function :
$('jQuery selector').css({"css property name":"css property value"});
If you don't want to use Jquery perhaps you could look on their plug-in how they coded it?

How to make image change on a hover

I've been trying to think of ways to do this but I haven't figured one out yet, so I thought I'd ask here!
So for example I have this:
<img src="arrow.png"/>Index
I want that on hovering Index, the image should change to arrow_hover.png, using CSS.
Use the pseudo class :hover
First, give the image a class so that it doesn't target every img. Say, hover-image
Then...
.hover-image:hover {
background: url('arrow_hover.png');
}
HOWEVER! THIS WILL NOT WORK! Using only CSS, you cannot change an images attribute src. You will need to use javascript.
You can change this to a div instead of an img tag, and this code will work. But not with your current markup.
To do this in javascript, give the element an id to make things easier. In this case.. derp.
You would do:
var x = document.getElementById("derp");
x.mouseenter = function() {
this.src = "arrow_hover.png";
}
x.mouseout = function() {
this.src = "arrow.png";
}
You could do this with CSS only. Try this CSS:
#theImage {
height:250px; //Or whatever size it needs to be
width:320px; //Or, again, whatever it needs to be
background-image:url(stuff.jpg);
}
#theImage:hover {
background-image:url(otherstuff.jpg);
}
#theImage would be a div.

jQuery image crossfade with pre-loader

I want a simple image crossfade, similar to http://malsup.com/jquery/cycle/, but with a pre-loader. Is there a good jQuery plugin that does both? Also, I'm not looking for a load bar.
This question is close, but not the same => jQuery Crossfade Plugin
It would be great if it was a solution that defaulted to CSS3, but would otherwise fall back to JS to keep the processing native as possible.
Looking for something that..
will autoplay
without controls
will go to the next image based on time setting, ie. 5 seconds, unless the next image isn't loaded in which case it finishes loading the image and then displays it.
crossfade transition, not fade to black or white, but cross-fade. from the start it would fadein.
no thumbnails or galleries, etc. just the image
If images could be CSS background images, that would be best, so users can't drag out the image simply
Each panel needs to be clickable so a user could click the image and go to a part of the website.
Well, here's my poke at it. The preloader is in vanilla js and the slideshow loop is in jQuery. It's very simple to implement and the concept is even simpler.
Demo
a very simple Demo that illustrates the DOM manipulation approach
HTML
<!-- not much here... just a container -->
<div id="content"></div>
CSS
/* just the important stuff here. The demo has example styling. */
#content
{
position:relative;
}
#content img
{
position:absolute;
}
javascript/jQuery
// simple array
var images = [
"http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_003t.jpg",
"http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_005t.jpg",
"http://imaging.nikon.com/lineup/dslr/d90/img/sample/pic_001t.jpg"
];
// some adjustable variables
var delay = 2000;
var transition = 1000;
// the preloader
for(var i in images)
{
var img = document.createElement("img");
img.src = images[i];
img.onload = function(){
var parent = document.getElementById("content");
parent.insertBefore(this,parent.childNodes[0]);
if(i == images.length - 1)
{
i = 0;
startSlides();
}
}
}
// and the actual loop
function startSlides()
{
$("#content img:last").delay(delay).fadeTo(transition,0,function(){
$(this).insertBefore($(this).siblings(":first")).fadeTo(0,1);
startSlides();
});
}
The concept in brief is to fade the first image in a container, once complete change it's position in the DOM (effectively hiding it behind equal tree level siblings), and call the function again. The reason why this works is because it only fades the first child of the container, but on callback it changes what node that is constantly looping the nodes. This makes for a very small source file that is quite effective.
EDIT 1:
and 32 minutes tweaking later...
Demo 2
EDIT 2:
My oh so simple script is now very complicated :P I added in some scaling features that only work on modern browsers but are there if needed. This one also has a loading bar as it preloads the images (may or may not be desirable :P)
small images demo
large images demo
I think you can still do this with the jQuery cycle plugin; other than image preloading, even the jQuery cycle lite version does everything you want by default out-of-the-box.
And if you look here, you'll see that it's pretty simple to add a little Javascript that will add images (after the first two) as they load. You would need to modify the code a little (instead of stack.push(this), you'd want something like stack.push("<div style="background-image:url("+img.src+")"></div>"), for example) but I think it's totally doable.
Edit: here's a link to a SO question about how to make a div into a clickable link.
Edit 2: I liked Joseph's idea to just move the elements to a hidden DIV, so I updated my code a bit. It now also preserves the links each div points to as well: http://jsfiddle.net/g4Hmh/9/
Edit 3: Last update! http://jsfiddle.net/g4Hmh/12/
UPDATE Added the ability to load everything asynchronously.
A wrapper for the jQuery cycle plugin should suffice. You really just need something that monitors if the images loaded and then calls $(elem).cycle(/* options */). Here's my take:
$.fn.cycleWhenLoaded = function(options) {
var target = this,
images = options.images,
loaded = 0,
total = 0,
i;
if(images) {
for(i = 0; i < images.length; i ++) {
$('<img/>').attr('src', images[i]).appendTo(target);
}
}
this.find('> img').each(function(index) {
var img = new Image(),
source = this;
total ++;
if(index > 1)
$(this).hide();
img.onload = function() {
loaded ++;
if(loaded == total) {
target.trigger('preloadcomplete');
target.cycle(options);
}
};
setTimeout(function() {img.src = source.src}, 1);
});
return this;
};
This allows you to either do a simple delay load:
$('.slideshow').cycleWhenLoaded({
fx: 'fade'
});
Or you can do something more complicated and load your images in the script and capture the preload complete event:
$('.slideshow2').hide().cycleWhenLoaded({
fx: 'fade',
images: [
"http://cloud.github.com/downloads/malsup/cycle/beach1.jpg",
"http://cloud.github.com/downloads/malsup/cycle/beach2.jpg",
"http://cloud.github.com/downloads/malsup/cycle/beach3.jpg",
"http://cloud.github.com/downloads/malsup/cycle/beach4.jpg",
"http://cloud.github.com/downloads/malsup/cycle/beach5.jpg"
]
}).bind('preloadcomplete', function() { $(this).show(); });
You can see it in action here: http://fiddle.jshell.net/vmAEW/1/
I don't know how close this is to what you are looking for, but I figured since no one else did I would at least try to help. http://galleria.aino.se/
It at least has a preloader and a fade transition.

Categories

Resources