I'm currently working on a site, where I want the background on the index (in this case an image.) to change every time you enter the site. So this is the solution that I came up with:
var Index = {
Actions: {
setBackground: function() {
var images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg'];
var random = images[Math.floor(Math.random() * images.length)];
alert(random);
$("body").css({'background-image': 'url("../img/backgrounds/' + random + '");'});
}
}
}
Index.Actions.setBackground();
but for some reason, the background stays white. I did also try the actual switching like this:
document.body.style.backgroundImage = "../img/backgrounds/" + random;
But that also did nothing.
Please note that the console is empty.
Here is the CSS for the body object:
body {
background-size:cover;
background-position:center;
background-attachment:fixed;
width:100%;
height:100vh;
position:relative;
}
Is there a reason that this wont work? And if so, how to fix it...
Thanks.
Try this; $("body").css('background-image', 'url("../img/backgrounds/' + random + '")');
jsfiddle demo
Correct syntax; .css( propertyName, value )
Related
I am working in a project where I need to generate a profile picture of any member and its reviews, and some data, I started working with GDI, but it was so hard to understand, so I searched for other options and found Html2Canvas that works with javascript/jquery, everything is fine, the only thing I couldn't handle, and would like to know if there is a way to hide the source html div without breaking the result image.
Ex:
This is how is it now
This is how it should look
So, when I apply display:none on the css of the source div, the image result is like this:
And finally here is the code that I have so far
var div_to_hide = $("#mydiv:hidden");
$(function() {
$('span.stars').stars();
});
html2canvas([document.getElementById('mydiv')], {
onrendered: function (canvas) {
document.getElementById('canvas').appendChild(canvas);
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
document.getElementById('image').appendChild(image);
}
});
$.fn.stars = function() {
return $(this).each(function() {
var val = parseFloat($(this).html());
val = Math.round(val * 4) / 4;
var size = Math.max(0, (Math.min(5, val))) * 16;
var $span = $('<span />').width(size);
$(this).html($span);
});
}
https://jsfiddle.net/ricardojriosr/6ap9Lx1f/8/
Now the question is how do I made this work showing only the image and not the HTML source. Thanks in advace.
Instead of trying to hide it before, hide (or remove) it after the canvas is rendered.
I'm not sure why var div_to_hide equals $("#mydiv:hidden"); but if you change it to var div_to_hide = $("#mydiv"); then, on line 12, after appending the image, you can run div_to_hide.hide();
And to avoid a flash of the HTML content, you can use some CSS trickery to cover up the original HTML. I made an example here, but you can adjust to fit whatever your actual needs are. https://jsfiddle.net/m5zq2kzn/
I had the same issue.
The solution that worked for me is a css trickery to position the div that I want to hide offscreen:
.offscreen {
position:absolute;
left:-10000px;
top:auto;
width:1px;
height:1px;
overflow:hidden;
}
Then use it like this:
html2canvas(document.getElementById("ticket_template"))
.then((canvas) => {
let imgData = canvas.toDataURL('image/png');
});
I created a function with the help of some other StackOverflow answers - when the button is clicked, it generates a random image from imgur by using a 5-letter string and adding it to a url. Here's my code: http://codepen.io/kaisle/pen/ojbwQm
function randomString() {
var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghiklmnopqrstuvwxyz';
var stringlength = 5;
var text = '';
for (var i = 0; i < stringlength; i++) {
var rnum = Math.floor(Math.random() * chars.length);
text += chars.substring(rnum,rnum+1);
}
document.getElementById('output').innerHTML = text;
var source = 'http://i.imgur.com/' + text + '.jpg';
$('.stuff img').attr('src', source);
var newimagewidth = $('.stuff img').width;
avoidBrokenImages();
}
This is successful besides the fact that I get the "removed" image a lot, because it's pulling deleted pictures from imgur, or images that never contained the random 5-letter string. To avoid this, I'm trying to create a way to detect this image (http://i.imgur.com/removed.png), which is 161px wide, and then re-run the function until it gets an image that is not 161px wide. I have attempted this in the Codepen above by running the following function at the end of my image generator function:
function avoidBrokenImages(){
var newimagewidth = $('.stuff img').width;
if ($('.stuff img').width() == 161) {
randomString();
} else {
return false;
}
}
This "avoidBrokenImages" function doesn't seem to work because I'm still getting the "removed" image a lot.
Any suggestions? I feel like this is something easy I'm missing.
You're trying to read the image width before it's loaded. You should change
$('.stuff img').attr('src', source);
var newimagewidth = $('.stuff img').width;
avoidBrokenImages();
to
$('.stuff img').attr('src', source).on('load', avoidBrokenImages);
Modified original: http://codepen.io/anon/pen/qObPrq
Slightly cleaned up code: http://codepen.io/anon/pen/KdVXWY
I'm making an image carousel i'm bounded to use background-image property instead of using
<img src="Image">
tag. my carousel is working if I use img tag . But its not working when I use background-image property, how can I modify my code with background-image property.
see my fiddle :https://jsfiddle.net/korLasen/ and update it please thanks :)
or you can see code here
(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
function imageSliderSet(){
image.setAttribute('data-background', imageSet[index]);
index++;
if(index >= imageSet.length){
index = 0;
}
}
setInterval = (imageSliderSet, 2000);
})();
This is quite a strange question... however, I am not one to judge :)
Here is a jsfiddle based on your example. I ended up using jquery for this. I hope this is somewhere near what you were looking for!
This is based on changing every two seconds. To extend that, you can change line 18 in the jquery. Here is the jquery:
$( document ).ready(function(){
var image = $('#imageSlider');
var imageSet = ['http://www.exposureguide.com/images/top-ten-tips/top-ten-photography-tips-1e.jpg','http://images.clipartpanda.com/cliparts-images-aTqyrB8TM.png'];
var index = 0;
window.setInterval(function(){
image.css('background-image', "url('" + imageSet[index] + "')");
index++;
if(index >= imageSet.length){
index = 0;
}
//here you can adjust the time interval for each photo
}, 2000);
});
I have a little trouble with a JavaScript piece of code.
The code is as it follows:`
$(switchBackground);
var oFReader = new FileReader(),
rFilter = /^(?:image\/bmp|image\/cis\-cod|image\/gif|image\/ief|image\/jpeg|image\/jpeg|image\/jpeg|image\/pipeg|image\/png|image\/svg\+xml|image\/tiff|image\/x\-cmu\-raster|image\/x\-cmx|image\/x\-icon|image\/x\-portable\-anymap|image\/x\-portable\-bitmap|image\/x\-portable\-graymap|image\/x\-portable\-pixmap|image\/x\-rgb|image\/x\-xbitmap|image\/x\-xpixmap|image\/x\-xwindowdump)$/i;
oFReader.onload = function(oFREvent) {
localStorage.setItem('b', oFREvent.target.result);
switchBackground();
};
function switchBackground() {
var backgroundImage = localStorage.getItem('b');
if (backgroundImage) {
$('#profile').css('background-image', 'url(' + backgroundImage + ')');
}
}
function loadImageFile(testEl) {
if (! testEl.files.length) { return; }
var oFile = testEl.files[0];
if (!rFilter.test(oFile.type)) { alert("You must select a valid image file!"); return; }
oFReader.readAsDataURL(oFile);
}
`
And my problem is the following, as I don't have almost any knowledge in JavaScript I'm having a hard time figuring out how to clone that code.
I have 2 <div>'s - one with id="profile" and the other with id="start-menu", I want the users of my web page to be able to change the background image of both <div>'s but untill now I have only been able to change the <div> with the id="profile". And the way that they change those backgrounds is through an input button, more exactly this one:
<input id="test" type="file" onchange="loadImageFile(this)" />
I have already tried adding some other characters to some of the functions names, and then just change id="test2" or onchange="loadImageFile2(this), but untill now I haven't been successful.
By the way, I should mention that I don't want the backgrounds to be changed with the same button, there are 2 diffrent input buttons, both with the same structure as above (except for the function calling they are almost the same).
What exactly do I need to change at the JS code above in order for it to work with both div's? Please be at your clearest when writing an answer, as my primar language is not english and sometimes I understand certaint phrases a bit harder.
This line is the important one:
$('#profile').css('background-image', 'url(' + backgroundImage + ')');
See the #profile part? That is a selector. That is telling the browser to change the background for the div with ID=profile. If you changed that to this:
$('#start-menu').css('background-image', 'url(' + backgroundImage + ')');
Then it would update the other div.
If you want it to update the two divs with the same images just do this:
function switchBackground() {
var backgroundImage = localStorage.getItem('b');
if (backgroundImage) {
$('#profile').css('background-image', 'url(' + backgroundImage +')');
$('#start-menu').css('background-image', 'url(' + backgroundImage +')');
}
}
If you wanted them to be separate images then you'd have to amend the switchBackground function to accept a parameter for which div to switch.
I'm trying to make some JavaScript code to change the background of two div tags every X seconds. Here is my code:
HTML
<div id="bg_left"></div>
<div id="bg_right"></div>
CSS
body{
height:100%;
}
#bg_left{
height:100%;
width:50%;
left:0;
position:fixed;
background-position:left;
}
#bg_right{
height:100%;
width:50%;
right:0;
position:fixed;
background-image:url(http://presotto.daterrawebdev.com/d/img/pp_hey_you_bg.png);
background-position:right;
}
JAVA SCRIPT
function carousel_bg(id) {
var bgimgs = [ 'pp_hey_you_bg.png', 'burningman_bg.png' ];
var img1 = bgimgs[id];
var img2 = bgimgs[id+1];
var cnt = 2;
$('#bg_left').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img1+")");
$('#bg_right').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img2+")");
id = id + 1;
if (id==cnt) id = 0;
setTimeout("carousel_bg("+id+")", 10000);
}
$(document).ready(function() {
carousel_bg(0);
});
The background-images should be changing randomly, but they don't even change at all.
OK, I see the issue in your jsFiddle. Because you're passing a string to setTimeout() that string will be evaluated only at the top level scope. But, the function name you were passing is not at the top level scope (it's in an onload handler for the jsFiddle). So, I changed the way your JS is positioned in the jsFiddle so it is now at the top level scope. I also fixed up the logic for selecting an image and it now works here: http://jsfiddle.net/jfriend00/awVYP/
And, here's a cleaned up version that does not pass a string to setTimeout() (a much better way to write javascript) that passes a local function and uses a closure to keep track of the current index: http://jsfiddle.net/jfriend00/LVGNN/
function carousel_bg(id) {
var bgimgs = [ 'pp_hey_you_bg.png', 'burningman_bg.png' ]; // add images here..
function next() {
if (id >= bgimgs.length) {
id = 0;
}
var img1 = bgimgs[id];
id++;
if (id >= bgimgs.length){
id = 0;
}
var img2 = bgimgs[id];
$('#bg_left').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img1+")");
$('#bg_right').css("background-image", "url(http://presotto.daterrawebdev.com/d/img/"+img2+")");
setTimeout(next, 1000);
}
next();
}
$(document).ready(function() {
carousel_bg(0);
});
Previous comments on earlier version so of the OP's code:
$('#body')
should be:
$('body')
or even faster:
$(document.body)
Also, your jsFiddle shows a bit of an odd issue. Your CSS has a background image on the HTML tag, but your javascript sets a semi-transparent background image on the body tag. Is that really what you want?
For testing I added another image to the array so that we got some distinction in the sorting.
function carousel_bg(id) {
var bgimgs = [ 'http://presotto.daterrawebdev.com/d/img/pp_hey_you_bg.png', 'http://presotto.daterrawebdev.com/d/img/burningman_bg.png', 'http://gallery.orobouros.net/var/albums/2012/NewYorkComicCon2012/Legend-of-Korra/nycc_20121013_164625_0041.jpg?m=1354760251' ]; // add images here..
var img1 = bgimgs[id+1];
var img2 = bgimgs[id];
var cnt = bgimgs.length; // change this number when adding images..
$('#bg_left').css("background-image", "url("+img1+")");
$('#bg_right').css("background-image", "url("+img2+")");
id = id + 1;
if (id== (cnt - 1) ) id = 0;
setTimeout("carousel_bg("+id+")", 10000);
}
Two changes here:
For your total image count, I am retrieving the total count of images in the array dynamically instead of by hand (bgimgs.length)
In your conditional to reset the id value, subtract the total count by 1. Since JS has zero-based indexes, not doing this will get you an undefined error (a 3 item array will spit out a value of 4 in your original code on the last iteration).
While this code does loop through your array, it's not random. That's another topic.
For those not using JQuery, simply do the following:
document.body.style.backgroundImage="url(images/mybackgroundimage.jpg)";