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?
Related
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/
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!
When I click a certain link I want the background-image to fadeOut, change to another image and then fadeIn.
The code I have:
$('.link').on('click',function(){
var image = $(this).data('image');
$('#div-with-the-bgimage').css('background-image', 'url('+image+')');
})
I tried this:
$('.link').on('click',function(){
var image = $(this).data('image');
$('#div-with-the-bgimage').fadeOut('3000').fadeIn('3000').css('background-image', 'url(' + image + ')');
})
but this didn't work, what am I doing wrong? (I'm new to jQuery)
EDIT:
I solved this with Rory McCrossan answer:
$('.link').on('click',function(){
var image = $(this).data('image');
$('#div-with-the-bgimage').fadeOut('3000', function() {
$(this).css('background-image', 'url('+image+')').fadeIn('3000');
});
});
But now this fadesOut to a white background and and then fadesIn to the image, giving a sensation of a flash? Is there a way to load the image before?
You need to chain the fades by calling the fadeIn after the fadeOut has completed. You can do this by using the callback function parameter. Try this:
$('.link').on('click',function(){
var image = $(this).data('image');
$('#div-with-the-bgimage').fadeOut('3000', function() {
$(this).css('background-image', 'url('+image+')').fadeIn('3000');
});
});
Wouldn't it be much simpler if you append / remove a div with the image you want and not change anything in the background? Just an example:
<div data-image="some-other-image.jpg" class="appendhere" style="position:relative">some content and an image background here</div>
Now using jQuery, you may put the image in the above data attribute on top, with 0 opacity, fade it in and out:
$('.link').on('click',function(){
var image = $(this).data('image');
var appendcode = '<div class="appended" style="display:none;position:absolute;width:200px;height:200px;overflow:hidden"><img src="' + image + '"></div>';
$('#div-with-the-bgimage').append(appendcode);
$('.appended').css({'opacity': 0, 'display':'block', 'z-index': 999}).fadeIn('3000', function() {
$(this).fadeOut('3000');
});
});
I used some inline styles there to point you need to make the wrapper relative positioned and the appended absolute positioned and with a higher z-index, you can make it much more elegant by including these in your CSS of course.
U can combine animate and opacity or use fadeOut and fadeIn functions.
Check out this link jsfiddle to see a working example using fadeOut and fadeIn.
U can also specify a unique img tag with data-gallery attribute storing multiple url's for images to toggle between all of them. Check this other link jsfiddle to see a working example. Click on the button Toggle to change the image.
Hope it useful!
I have a script which generates a random number so that when setImg(); is called a randomly selected image appears:
<img src="" id="imgRand" alt="">
function setImg(){
var numRand = Math.floor(Math.random()*(6 - 1 + 1)) + 1;
document.getElementById("imgRand").src = "images/"+numRand+".jpg";
}
This all works fine, but when the image changes, it just 'appears'. I was wondering if there was any way to get it to fade from one to the other? Everything I've found online talks about setting styles on each individual image, but as Im using this random number script to source my images, I cant think of a way to adapt any of those solutions.
Any help is much appreciated, thanks!
I will provide you with an example using CSS3 transitions. You can adapt and improve it for your specific case.
My specific example works only with Webkit as it is written since the implementation of the transcription end callback is vendor dependent. You can fix this by using the correct vendor event handler names.
/* Fades an element to given opacity */
var fade = function(opacity, fn) {
this.addEventListener("webkitTransitionEnd", function end() {
this.removeEventListener("webkitTransitionEnd", end);
fn && fn.call(this);
}, false);
this.style.opacity = opacity;
};
/* Preloads an image */
var load = function(src, fn) {
var self = this, $img = new Image();
$img.onload = function() {
fn && fn.call(self);
};
$img.src = src;
};
/* Steps:
* 1. Fades out current image.
* 2. Preloads next image.
* 3. When loading of next image is complete, sets next image.
* 4. Fades in.
*/
var $img = document.getElementById("imgRand");
/* Fades out */
fade.call($img, 0, function() {
/* Get random dimensions */
var height = Math.ceil(Math.random() * 100) + 100;
var width = Math.ceil(Math.random() * 200) + 100;
var src = "http://placehold.it/" + width + "x" + height;
/* Preloading */
load.call(this, src, function() {
$img.setAttribute("src", src);
/* Fades in */
fade.call($img, 1);
});
});
You can see it here.
The img element has -webkit-transition-duration style property set to 1s.
The most complicated and overlooked part of this is image preloading. Because, unless you preload all images that you want to use, the animation won't be smooth. But at the same time the detection of when an image has been loaded is not an easy task and the method that I'm using is a naive one that most probably will fail for images in the browser's cache. I won't go into details about that, you can search SO for it.
Disclaimer: It is too freaking late. So, I will just dump the code here and come to it later. If there's doubts.
This can be done most easily using a library such as jQuery but here is a jsFiddle example. I use absolute positioning to have two images placed over the top of each other and give one of them an opacity of 0. Then I just toggle between the two and fade one in and one out using helper functions.
The html looks something like this:
<div id="imageHolder">
<img id="imgRand0" src="http://placehold.it/100x100" />
<img id="imgRand1" src="http://placehold.it/100x100" style="opacity:0;alpha(opacity:0);"/>
</div>
<button onclick="setImg()">New Image</button>
The CSS:
img {
position:absolute;
top:0;
left:0;
}
#imageHolder {
position:relative;
height:100px;
}
And the javascript (I use additional functions from this tutorial):
var counter = 0;
function setImg(){
var numRand = Math.floor(Math.random()*6) + 1;
//document.getElementById("imgRand").src = "images/"+numRand+".jpg";
counter = (counter + 1) % 2;
document.getElementById("imgRand" + counter).src = "http://placehold.it/100&text=" + numRand;
fade('imgRand0');
fade('imgRand1');
}
This was too long to put into a comment, but hopefully it will guide you in the right direction.
So, because you're replacing the src of imgRand with each call to setImg, the two images you're trying to cross-fade will not be present in the DOM at the same time. You will probably need to have two separate image tags that are stacked on top of each other with CSS.
Then you will need to set the src on the top image (the one you want to fade in) and hide this image with CSS or your image will just 'appear' as soon as you set the src.
Then you will want to fade the top image in incrementally by setting the opacity of the image until it's 100...
Sorry for such a crazy description, but it's probably far easier if you have jQuery available. I will go and hunt down an example and update this.
Update: If you have jQuery, this is a rudimentary example of what your script might look like: http://jsfiddle.net/tracyfu/W9wMh/ Some of the other solutions here might be better if you're confined to straight JS.
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)