js body random background image - javascript

This code should use any .jpg image from /images/bg/ folder, however it doesn't seems to be taking images below particular resolution...any suggestions?
<!--random background images from a folder-->
<script type="text/javascript">
var totalCount = 5;
function ChangeIt() {
var num = Math.ceil(Math.random() * totalCount);
document.body.background = 'images/bg/' + num + '.jpg';
document.body.style.backgroundSize = "cover";
}
</script>

Demo
document.body.background is deprecated, it should be document.body.style.background and the format you're giving it is wrong. Try
document.body.style.background = 'url(images/bg/' + num + '.jpg)';
The following also works and doesn't remove the other attributes of background, like backgroundSize for example, so you wouldn't need the line document.body.style.backgroundSize = "cover"; as long as it was set in the first place.
document.body.style.backgroundImage = 'url(images/bg/' + num + '.jpg)';
So, your code would read
<script type="text/javascript">
document.body.style.backgroundSize='cover';
document.body.style.backgroundRepeat='no-repeat'; // i've assumed this
var totalCount = 5;
function ChangeIt() {
var num = Math.ceil(Math.random() * totalCount);
document.body.style.backgroundImage = 'url(images/bg/' + num + '.jpg)';
}
</script>
Though, ideally you'd set cover and no-repeat in a CSS file.

Use document.body.style.backgroundImage = "url('" + 'images/bg/' + num + '.jpg' + ")";
(google about css background image).

Related

How to make "Download Background Image" button in JavaScript?

I made a random background color generator in HTML/JavaScript. Now, I want to add "Download Background Image" button. But I don't know how.
Here is my code:
function randomBgColor() {
var rmin = +rmintxt.value;
var rmax = +rmaxtxt.value;
var gmin = +gmintxt.value;
var gmax = +gmaxtxt.value;
var bmin = +bmintxt.value;
var bmax = +bmaxtxt.value;
var r = Math.floor(Math.random() * (rmax - rmin + 1) + rmin);
var g = Math.floor(Math.random() * (gmax - gmin + 1) + gmin);
var b = Math.floor(Math.random() * (bmax - bmin + 1) + bmin);
var r2 = Math.floor(Math.random() * 255);
var g2 = Math.floor(Math.random() * 255);
var b2 = Math.floor(Math.random() * 255);
var rhex = r.toString(16);
var ghex = g.toString(16);
var bhex = b.toString(16);
var bgColor = "rgb(" + r + "," + g + "," + b + ")";
var bgColor2 = "rgb(" + r2 + "," + g2 + "," + b2 + ")";
document.body.style.background = bgColor;
rgb.innerHTML = "RGB: " + r + ", " + g + ", " + b;
rgb.style.color = bgColor2.toString(16);
hex.innerHTML = "Hex: #" + rhex.toUpperCase() + ghex.toUpperCase() + bhex.toUpperCase();
hex.style.color = bgColor2.toString(16);
}
I don't know why it doesn't work on StackOverflow, but on my computer it works well. Try to copy-paste and check it out.
var theCanva = document.querySelector('canvas');
var twoD = theCanva.getContext("2d");
var theBtn = document.querySelector('.btn');
function random_rgba() {
var o = Math.round, r = Math.random, s = 255;
return 'rgba(' + o(r()*s) + ',' + o(r()*s) + ',' + o(r()*s) + ',' + r().toFixed(1) + ')';
}
twoD.width = window.innerWidth;
twoD.height = window.innerHeight;
var link = document.createElement('a');
link.innerHTML = 'Download';
link.addEventListener('click', function(ev) {
link.href = theCanva.toDataURL("image/png");
link.download = "test";
}, false);
theBtn.addEventListener('click', () => {
var color = random_rgba();
twoD.fillStyle = color;
twoD.fillRect(0, 0, 1200, 800);
document.body.appendChild(link);
});
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
canvas {
position: fixed;
width: 100%;
height: 100vh;
z-index: -1;
left: 0;
right: 0;
top: 0;
bottom: 0;
}
<button class="btn">Generate random background color</button>
<canvas></canvas>
If you would like to have the button be able to have a file selector where you could make the page's background be the selected image, then you would need to have a file input, so that you can get the image that the user would like to use as a background to be displayed. In the JS, then you will need to create a variable to get the data of what the chosen file is. Now, you will need to have a conditional that checks if there even is a picture. So you can just do this:
if (/**Over here, you must check if the file exists and it is an image.**/) {
//Over here, you would want to turn the page's background into the image.
}
But, you need to have a function, or else the whole thing will only run at the very start of the page's load. You need to add an event listener or something that checks when the file is chosen. If you don't know how to do that, then you can just search it up. Or, you could find something on Stack Overflow that relates to it. Like this:
How to check if input file is empty in jQuery
Hope this helps! If you have any further questions, please tell me. I am new on Stack Overflow, so I need to know how I can improve. Thanks!

Javascript - window.open() popup size issue

I am trying to display preloaded images in a newly created popup window. Here is the code:
HTML
<div id="hiddenImages" style="display: none;"></div>
<img src="SmallImage1.gif" width="196" height="130" border="0">
<img src="SmallImage2.gif" width="196" height="130" border="0">
JS
<script type="text/javascript">
preloadImages('BigImage1.png','BigImage2.png');
</script>
// PreLoadImages:
function preloadImages() {
var hiddenDiv = document.getElementById('hiddenImages');
var i;
var img;
for(i = 0; i < arguments.length; i++) {
img = document.createElement('img');
img.src = arguments[i];
img.id = arguments[i];
img.alt = '';
hiddenDiv.appendChild(img);
}
}
// OpenImage:
function OpenImage(element,e)
{
e.preventDefault();
var big_image = element.getAttribute("href");
var img = document.getElementById(big_image);
var top = (screen.height/2)-(img.height/2);
var left = (screen.width/2)-(img.width/2);
var str = "\"" + "width=" + img.width + ",height=" + img.height + ",top=" + top + ",left=" + left + ",status=0, scrollbars=0, resizable=0" + "\"";
alert(str);
var myWindow = window.open(img.src , "win1", str);
}
When I output 'str' variable in OpenImage() function, this code gives perfect dimensions of the big image. However, the size of popup window is always different than size of the image. IE stretches the popup window horizontally while Google Chrome stretches it vertically. In spite of the fact that both browsers show exactly the same dimensions for the image. And these dimensions of the image are actually being set as size of the pop up window.
Regards.
Try this out, also try to rename your variable top, I think javascript read this as a keyword.
var str = "width=" + img.width + ",height=" + img.height + ",top=" + tops + ",left=" + left + ",status=0, scrollbars=0, resizable=0 ";

Jquery .each() giving me values of all elements with the same class

Please go to: www.designedbychristian.com/template_2
(so far being tested in chrome)
When you click design a bunch of thumbnails appear.
I am trying to use the .each selector to get the src of the image. I want to take that value and apply it to a div that will appear when clicked. (I know how to program that part)
My problem is when I click the thumb nail my alert is giving me the value of all of the thumbnails.
my code is this:
function spawnImages() {
N = 1
for (i = 1; i <= 9; i++) {
var gal = document.getElementById('gallary')
var newDIV = '<img onclick="imageView()" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
$('.gallary').prepend(newDIV)
var min = 3;
var max = 70;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' +N)).css("left", s + "%")
var min = 3;
var max = $(this).height();
var max = 70;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' + N)).css("top", s + "%")
var min = -45;
var max = 45;
var s = Math.floor(Math.random() * (max - min + 1)) + min;
var test = $(('.imageNumber' + N)).css("-webkit-transform", "rotate(" + s + "deg)")
var test = $(('.imageNumber' + N)).css("transform", "rotate(" + s + "deg)")
var test = $(('.imageNumber' + N)).css("-ms-transform", "rotate(" + s + "deg)")
N++
}
}
function imageView() {
$(".thumb-nail").each(function () {
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
})
};
Just use jquery event handlers, get rid of the onclick call in your html and just add this in your javascript.
$(".thumb-nail").on('click', function(){
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
});
EDIT: didn't think about the images being created dynamically, Popnoodles answer is the right one
pass clicked element reference like this:
var newDIV = '<img onclick="imageView(this)" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
Function:
function imageView(element) {
var imageSrc = $(element).attr('src');
alert($(element).attr('src'));
}
This is exactly how the jQuery API describes the .each() method:
Iterate over a jQuery object, executing a function for each matched element.
When you called $('.thumb-nail') it returned ALL of the elements with the class thumb-nail in a jQuery object. Then when you called .each( function() {} ) on that object, the loop iterated over all of the returned elements.
The easiest way to handle click events in jQuery, is to use the .on() method, as others have pointed out in their answers.
Also, as #Popnoodles mentioned, since these elements are created dynamically, you may need to run your $().on() call explicitly after these elements are created. For that reason, you might wrap it into your spawnImages() function, rather than putting it inside $() as #Popnoodles indicates (i.e. not $( $(element).on('click',function(){}), as $( ) is equivalent to $(document).ready.
The simplest change is this
// send this element to the function
var newDIV = '<img onclick="imageView(this)" src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
function imageView(el) {
var imageSrc = $(el).attr('src');
alert($(el).attr('src'));
};
But it's nice to do things in a more standard fashion...
First get rid of this onclick="imageView()"
var newDIV = '<img src="images2/image' + N + '.jpg" class="thumb-nail imageNumber' + N + '"/>'
Since these elements are created dynamically you will need to bind the click event to document or another ancestor that exists, and delegate to each ".thumb-nail".
You also need to run this procedure only when dom is ready ($(function(){...});).
$(function(){
$(document).on('click', ".thumb-nail", function () {
var imageSrc = $(this).attr('src');
alert($(this).attr('src'));
//$('.images').css("background-image", "url("+imageSrc+")");
//$('.images').css("background-size", "cover");
//$('.blackForeground').css("visibility", "visible");
//$('.images').css("visibility", "visible");
});
});

jQuery Prevent Loading same image twice in a row

I am using a good bit of jQuery to create a CSS fade effect on a website. It works really well. But as it only has 4 images in the array, It is quite likely loading the same image twice in a row.
What can I add to prevent this?
My current jQuery code is as follows :
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var nextBG = "url(" + imgArray[Math.floor(Math.random() * imgArray.length)] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
nextBG = "url(" + imgArray[Math.floor(Math.random() * imgArray.length)] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval
Thanks in advance.
Cheers
You can show your images one after another (and repeat this the whole time):
var counter = 0;
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var nextBG = "url(" + imgArray[counter] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
counter++;
nextBG = "url(" + imgArray[counter % imgArray.length] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval
or choose randomly:
// Playthrough Background Images
var imgArray = ['http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner1.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner2.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img//home/banner3.jpg',
'http://www.jesmonddenehouse.co.uk/addons/shared_addons/themes/jesmonddene/img/home/banner4.jpg'
]
var current = Math.floor(Math.random() * imgArray.length);
var nextBG = "url(" + imgArray[current] + ")";
$('#header.home-page').css("background-image", nextBG);
setInterval(function(){
var copy = imgArray.slice(0); // make copy
copy.splice(current, 1); // remove current
current = Math.floor(Math.random() * copy.length);
nextBG = "url(" + copy[current] + ")";
$('#header.home-page').fadeOut('fast', function() {
$(this).css("background-image", nextBG).fadeIn('fast'); })
}, 4000); // 4 second interval

Why are my pictures not opening in a separate window?

Heres the Javascript code:
function showCard(linkTarget) {
var propertyWidth = 400;
var propertyHeight = 350;
var winLeft = (screen.width-propertyWidth)/2;
var winTop = (screen.height-propetyHeight)/2;
var winOptions = "toolbar=no,menubar=no,location=no,scrollbars=yes,resizable=no";
winOptions += ",width=" + propertyWidth;
winOptions += ",height=" + propertyHeight;
winOptions += ",left=" + winLeft;
winOptions += ",winTop=" + winTop;
cardWindow = window.open(link.target,"cardInfo", winOptions);
cardWindow.focus();
}
var cardWindow;
href="valentine.jpg" onclick="showCard('valentine.jpg');return false">Valentine's Day
(I removed the tags because the code is not showing up with them)
window.open(link.target...) should be window.open(linkTarget...)
This is causing an error, so the return false; is never reached and the link navigates as normal.
Looks to me like your problem is here:
Your function is declared as:
function showCard(linkTarget)
but you refer to the parameter passed in later in the code with a dot as
cardWindow = window.open(link.target,"cardInfo",winOptions);

Categories

Resources