change background when refreshed, but responsive - javascript

i currently have this javascript code in my head tag which makes the background change every time the page is refreshed. it works great, however, i would like to have different "image sets" (1.png, 2.png, 3.png vs 1mini.png, 2mini.png, 3mini.png), one for the desktop version and another one for the mobile version. any idea on how to do this?
<script>
function changeImg(imgNumber) {
var myImages = ["images/1.png", "images/2.png", "images/3.png",
"images/1mini.png", "images/2mini.png", "images/3mini.png" ];
var imgShown = document.body.style.backgroundImage;
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.body.style.backgroundImage = 'url('+myImages[newImgNumber]+')';}
window.onload=changeImg;
</script>

`You can go for some queries depending on your device viewport.`
function changeBg(){
var width = window.innerWitdh;
var myImages = ["images/1.png", "images/2.png", "images/3.png",
"images/1mini.png", "images/2mini.png", "images/3mini.png" ];
if(width > 1200){ // lets say here is a desktop
document.body.style.backgroundImage = 'url('+ myImages[1] +')';
}else if(width < 1200 && width > 700){ // some smaller device
document.body.style.backgroundImage = 'url('+ myImages[2] +')';
}else { // this can be mobile
document.body.style.backgroundImage = 'url('+ myImages[3] +')';
}
}

Working Example
function changeImg(imgNumber) {
var myImages = [{
isMobile: true,
image: "https://cdn.pixabay.com/photo/2016/04/15/04/02/water-1330252__340.jpg"
},
{
isMobile: false,
image: "https://images.pexels.com/photos/531880/pexels-photo-531880.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"
},
{
isMobile: true,
image: "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTptDddyBZG4i4cycd6ZIBP2wT8PQKhihUqenZF7GpzlvTZuPghGQ"
},
{
isMobile: false,
image: "http://sfwallpaper.com/images/background-wallpaper-images-3.jpg"
}
];
var imgShown = document.body.style.backgroundImage;
var filteredArray = [];
if (isMobile()) {
filteredArray = myImages.filter(function(el) {
return el.isMobile == true;
});
} else {
filteredArray = myImages.filter(function(el) {
return el.isMobile == false;
});
}
var newImgNumber = Math.floor(Math.random() * filteredArray.length);
console.log("newImgNumber", newImgNumber);
document.body.style.backgroundImage = 'url(' + filteredArray[newImgNumber].image + ')';
}
function isMobile() {
var match = window.matchMedia || window.msMatchMedia;
if (match) {
var mq = match("(pointer:coarse)");
return mq.matches;
}
return false;
}
window.onload = changeImg;

You can use media query with different css class that could be use as a background.
#media screen and (max-width: 768px) {
.img1 {
background-image: url("1.jpg");
}
.img2 {
background-image: url("2.jpg");
}
}
.img1 {
background-image: url("3.jpg")
}
.img2 {
background-image: url("4.jpg");
}
And change shown classes with function.
So you have one function and it is responsive for window size without any additional methods - simply in css file.
EDIT:
<script>
function changeImg(imgNumber) {
var myImages = ["img1", "img2", "img3"];
var newImgNumber =Math.floor(Math.random()*myImages.length);
document.getElementByClassName(myImages[newImgNumber]).show();}
window.onload=changeImg;
</script>
And you put display:none; in your css file. So you show only background that was 'randomly' picked.
<html>
<div class='background'>
<div class="img1"/>
<div class="img2"/>
<div class="img3"/>
Something like that.

You can set the background image by checking if the device is mobile or desktop.
eg:
i currently have this javascript code in my head tag which makes the background change every time the page is refreshed. it works great, however, i would like to have different "image sets" (1.png, 2.png, 3.png vs 1mini.png, 2mini.png, 3mini.png), one for the desktop version and another one for the mobile version. any idea on how to do this?
<script>
function changeImg(imgNumber) {
var mobileImages =["images/1mini.png","images/2mini.png","images/3mini.png"];
var desktopImages = ["images/1.png", "images/2.png", "images/3.png"];
var imgShown = document.body.style.backgroundImage;
//this code will return true when device is mobile
if (navigator.userAgent.match(/(iPad)|(iPhone)|(iPod)|(android)|(webOS)/i)) {
var newImgNumber =Math.floor(Math.random()*mobileImages.length);
document.body.style.backgroundImage =
'url('+mobileImages[newImgNumber]+')';
}else{
var newImgNumber =Math.floor(Math.random()*desktopImages.length);
document.body.style.backgroundImage =
'url('+desktopImages[newImgNumber]+')';
}
}
}
window.onload=changeImg;
</script>

Related

changing a Javascript image on event listener click

i have a Div holding an image with the id sunset that i want to add an onclick to to change its width from the CSS 25% to 100%
cannot see why my code is not working
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click) {
content.style.width = "100%";
}
else {
content.style.width = "25%";
}
});
CSS
#sunset{
width:25%
}
The first if statement doesn't check if the first_click var is true (assuming that is what you intend to do). Since it is empty it would return false and the else statement would run, keeping your image at 25%.
try this:
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click == true) {
content.style.width = "100%";
}
else {
content.style.width = "25%";
}
});
Have you tried adding height to your container ? This should work
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function () {
if (first_click) {
content.style.width = "100%";
first_click = false;
}
else {
content.style.width = "25%";
}
});
#sunset{
width:25%;
background: #000;
height: 200px;
}
<div id="sunset"></div>
The problem is that you're not toggling the first_click variable to true or false when the image is clicked. The code below fixes this by setting first_click = !first_click:
var content = document.getElementById("sunset");
var first_click = true;
content.addEventListener("click", function() {
if (first_click) {
content.style.width = "100%";
} else {
content.style.width = "25%";
}
first_click = !first_click;
});
#sunset {
width: 25%
}
<img id="sunset" src="https://dummyimage.com/150/f8f">

Force duplicate printElement to go to the bottom part of the page using window.print();

I am planning to do a duplicated printing. The top-half is for the staff's copy, and the lower-half part is for the user's copy. We will just cut the paper in half once it's printed. How do we do this? Can the window.print(); do this?
This is the script that I am using.
function PrintAppendChangeScheduleButton() {
printElement(document.getElementById("divID")); //Specify the DIV to be printed.
function printElement(elem) {
var forDOMClone = elem.cloneNode(true);
var $forSECTIONPrint = document.getElementById("forSECTIONPrint"); //For Section Specific Print
if (!$forSECTIONPrint) {
var $printSection = document.createElement("div"); //For DIV Specific Print
$forSECTIONPrint.id = "forSECTIONPrint";
document.body.appendChild($forSECTIONPrint);
} else {
$forSECTIONPrint.innerHTML = "";
$forSECTIONPrint.appendChild(forDOMClone);
window.print();
return true;
}
}
}
I tried duplicating elem.cloneNode(true);, but it does not arrange it properly.
This is what I'm working on right now.
function PrintAppendChangeScheduleButton() {
printElement(document.getElementById("divID")); //Specify the DIV to be printed.
function printElement(elem) {
var forDOMClone = elem.cloneNode(true);
var forDOMCloneCUT = elem.cloneNode(true);
var $forSECTIONPrint = document.getElementById("forSECTIONPrint"); //For Section Specific Print
if (!$forSECTIONPrint) {
var $printSection = document.createElement("div"); //For DIV Specific Print
$forSECTIONPrint.id = "forSECTIONPrint";
document.body.appendChild($forSECTIONPrint);
} else {
$forSECTIONPrint.innerHTML = "";
$forSECTIONPrint.appendChild(forDOMClone);
$forSECTIONPrint.appendChild(forDOMCloneCUT);
window.print();
return true;
}
}
}
This is the current printing status.
This is the result that I am looking for.
Is there a way for javascript to force $forSECTIONPrint.appendChild(forDOMCloneCUT); to go to the lowest part of the page?
I have hacked something together.
First, we need to know that the size of an A4 sheet is 210mm x 297mm. I got that from here.
Next, we need to convert the height (297mm) to pixels. We do that here and get 1122.5px.
Now we need to measure the height of the div you want to print twice, and see if twice the height of the div is less than the size of an A4 sheet. If yes, then we create an empty div in between the 2 clones and give it the height of whatever empty space is there after the clones.
So here's your modified code:
* {
margin: 0;
padding: 0
}
<div id='divID' style="border: 2px black solid; padding-bottom: 200px">
<h1>CONTENT FROM THIS PAGE IS FROM printElement(document.getElementById('div1'))</h1>
</div>
<div id='forSECTIONPrint'></div>
<script type="text/javascript">
window.onload = PrintAppendChangeScheduleButton;
function PrintAppendChangeScheduleButton() {
printElement(document.getElementById("divID")); //Specify the DIV to be printed.
function printElement(elem) {
var forDOMClone = elem.cloneNode(true);
var forDOMCloneCUT = elem.cloneNode(true);
var $forSECTIONPrint = document.getElementById("forSECTIONPrint"); //For Section Specific Print
if (!$forSECTIONPrint) {
var $printSection = document.createElement("div"); //For DIV Specific Print
$forSECTIONPrint.id = "forSECTIONPrint";
document.body.appendChild($forSECTIONPrint);
} else {
$forSECTIONPrint.innerHTML = "";
var elemHeight = elem.offsetHeight;
elem.style.display = 'none';
var emptySpace = document.createElement('div');
$forSECTIONPrint.appendChild(forDOMClone);
$forSECTIONPrint.appendChild(emptySpace);
//if there's any empty space at the bottom of the page, then set the height of the
//empty div in between the clones with that space height
if (1122.5 - (elemHeight * 2) > 0){
setTimeout(function(){
emptySpace.style.height = 1122.5 - (elemHeight * 2) + 'px';
window.print();
},100);
}
//if there's no empty space, just print right away
else {
window.print();
}
$forSECTIONPrint.appendChild(forDOMCloneCUT);
return true;
}
}
}
</script>

Javascript Automatic Image Swap w/ Multiple Arrays

I'm currently working on an image rotator. The rotation part is complete, however I'm expanding the functionality based on a need that I've found.
Goal: Rotate through a preset list of slides that contain hardcoded images, however on each subsequent rotation, use js to swap to a new image for specific slides that require a variation.
The script below works fine, but I feel like it's not the most efficient way to go about this. Currently I'm tackling it by running a new loop and function for each of the specific slides that I've chosen to be the "different" ones. My guess is there is a way to do it using one function and loop, but I'm not quite sure how to go about it.
Anology: Let's say I have an image rotator that displays a list of cars and every 5 seconds it rotates to the next slide. Each slide is designated for a different model of car, however for some models, I want to display a different variation of that model on each iteration of the entire rotator.
Example:
Here is a list of how each pass of the rotator would print.
- Ford Focus
- Toyota Celica
- Hyundai Elantra
- Dodge Ram
- Motorcycle
- Ford Focus
- Toyota Celica GTS
- Hyundai Elantra
- Dodge Ram w/ additional accessories
- Motorcycle
- Ford Focus
- Toyota Celica w/ Spoiler
- Hyundai Elantra
- Dodge Ram different color
- Motorcycle
Here is my current script:
<script>
window.onload=function() {
imgCont = document.getElementById('example1');
c_imgCont = document.getElementById('example2');
}
var myIndex = 0;
carousel();
function carousel() {
var i;
var x = document.getElementsByClassName("slide");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
myIndex++;
if (myIndex > x.length) {myIndex = 1;
if (typeof(imgCont) != 'undefined' && imgCont != null)
{
swapImage();
}
if (typeof(c_imgCont) != 'undefined' && c_imgCont != null)
{
swapImageExample2();
}
}
x[myIndex-1].style.display = "block";
setTimeout(carousel, x[myIndex-1].dataset.timing);
}
var picPaths = ['image1.png','img2.png','img3.png','img4.png'];
var curPic = -1;
//preload the images for smooth animation
var imgO = new Array();
for(i=0; i < picPaths.length; i++) {
imgO[i] = new Image();
imgO[i].src = picPaths[i];
}
function swapImage() {
curPic = (++curPic > picPaths.length-1)? 0 : curPic;
imgCont.src = imgO[curPic].src;
}
var c_picPaths = ['otherimg1.png','otherimg2.png'];
var c_curPic = -1;
//preload the images for smooth animation
var c_imgO = new Array();
for(l=0; l < c_picPaths.length; l++) {
c_imgO[l] = new Image();
c_imgO[l].src = c_picPaths[l];
}
function swapImageExample2() {
c_curPic = (++c_curPic > c_picPaths.length-1)? 0 : c_curPic;
c_imgCont.src = c_imgO[c_curPic].src;
}
</script>
Why not just adjust your data structure so that any "image" in the picPaths array can be an array of image paths. Then use a function to get the image path to show. See simple example below.
Notice the structure of picPaths. Also notice that the 2nd and 4th images in the rotation (transport, nature) rotate through different images each iteration of the picPaths array.
<img id="example1" src="http://lorempixel.com/400/200/cats/1/"/>
<script>
window.onload = function() {
imgCont = document.getElementById('example1');
swapImage();
}
var picPaths = [
"http://lorempixel.com/400/200/cats/1/",
[
"http://lorempixel.com/400/200/transport/1/",
"http://lorempixel.com/400/200/transport/2/",
"http://lorempixel.com/400/200/transport/3/",
"http://lorempixel.com/400/200/transport/4/"
],
"http://lorempixel.com/400/200/animals/1/",
[
"http://lorempixel.com/400/200/nature/1/",
"http://lorempixel.com/400/200/nature/2/",
"http://lorempixel.com/400/200/nature/3/",
"http://lorempixel.com/400/200/nature/4/",
"http://lorempixel.com/400/200/nature/5/"
],
"http://lorempixel.com/400/200/sports/1/"
],
curImg = 0;
function getImagePath(path) {
if(Array.isArray(path)) {
var temp = path.shift();
path.push(temp);
return temp;
}
else {
return path;
}
}
function swapImage() {
curImg = curImg < (picPaths.length - 1) ? curImg : 0;
var imgPath = getImagePath(picPaths[curImg]);
console.clear();
console.log('current index in picPaths:', curImg, 'current image path to display:', imgPath);
imgCont.src = imgPath;
curImg++;
setTimeout(function() {
swapImage();
}, 4000);
}
</script>
Based on your comment I made a 2nd example. I think this is what you mean.
window.onload = function() {
carousel(picPaths, 'slide');
};
var picPaths = [
"https://placeimg.com/640/480/any/sepia/1",
[
"https://placeimg.com/640/480/tech/1",
"https://placeimg.com/640/480/tech/2",
"https://placeimg.com/640/480/tech/3",
"https://placeimg.com/640/480/tech/4"
],
"https://placeimg.com/640/480/animals/1",
[
"https://placeimg.com/640/480/nature/1",
"https://placeimg.com/640/480/nature/2",
"https://placeimg.com/640/480/nature/3",
"https://placeimg.com/640/480/nature/4",
"https://placeimg.com/640/480/nature/5"
],
"https://placeimg.com/640/480/arch/1"
];
function carousel(imgPaths, imgClass) {
var imgs = document.getElementsByClassName(imgClass);
Array.prototype.forEach.call(imgs, function(imgElem, idx) {
var timing = imgElem.dataset.timing,
path = imgPaths[idx];
swapImage(imgElem, path, timing);
});
function getImagePath(path) {
if(Array.isArray(path)) {
var temp = path.shift();
path.push(temp);
return temp;
}
else {
return path;
}
};
function swapImage(imgElem, path, timing) {
var imgPath = getImagePath(path);
imgElem.src = imgPath;
setTimeout(function() {
swapImage(imgElem, path, timing);
}, timing);
};
}
.slide {
width: 100px;
}
<div id="container">
<img id="slide_1" class="slide" src="" data-timing="8000">
<img id="slide_2" class="slide" src="" data-timing="4000">
<img id="slide_3" class="slide" src="" data-timing="10000">
<img id="slide_3" class="slide" src="" data-timing="6000">
</div>

Creating Dynamic Fullscreen and Minimize Div Functions

The screen displays 3 dynamically created and loaded divs. The problem I'm having is getting the resize to work when I try to make the divs go full screen. (Click the front button and the 2nd on the back). When using the select option on top, the resize works perfectly, but the fullscreen does not have the same effect.
This is my plunkr: http://plnkr.co/edit/qYxIRjs6KyNm2bsNtt1P
This is my current resize function:
for(i = 0; i<numOfDivs.length; i++){
var flipTarget = document.getElementById(flipDiv[i]);
addResizeListener(flipTarget, function() {
for(j = 0; j<numOfDivs.length; j++){
var style = window.getComputedStyle(flipTarget);
divWidth = parseInt(style.getPropertyValue('width'), 10);
divHeight = parseInt(style.getPropertyValue('height'), 10);
width = divWidth - margin.left - margin.right;
height = divHeight - margin.top - margin.bottom;
document.getElementById(frontDivNames[j]).innerHTML = '<span style="font-size: 40px; font-family:icons; cursor:pointer" id="flip" onclick="flipper(\''+flipperDivNames[j]+'\')"></span>';
makeTestGraph();
makeSliderGraph();
};
});
}
Any help on hiding all the other divs and making them reappear later would also be greatly appreciated. This has taken a few days of work and I have gotten almost nowhere despite rewriting the code several times.
Thanks for the help.
Is there something wrong with the javascript fullscreen api???
<script>
var fullscreen;
SetFullscreen = function DetectFullscreen(el){
DesktopFullScreen = function ToggleFullScreen(el){
function cancelFullScreen(el) {
if (window.document.exitFullscreen) {
window.document.exitFullscreen();
} else if (window.document.webkitExitFullscreen) {
window.document.webkitExitFullscreen();
} else if (window.document.mozCancelFullScreen) {
window.document.mozCancelFullScreen();
} else if (window.document.msExitFullscreen) {
window.document.msExitFullscreen();
}
return undefined;
}
function requestFullScreen(el) {
// Supports most browsers and their versions.
var requestMethod = document.getElementById(el).requestFullScreen || document.getElementById(el).webkitRequestFullScreen || document.getElementById(el).mozRequestFullScreen || document.getElementById(el).msRequestFullscreen;
if (requestMethod) { // Native full screen.
requestMethod.call(document.getElementById(el));
} else if (typeof window.ActiveXObject !== "undefined") { // Older IE.
var wscript = new ActiveXObject("WScript.Shell");
if (wscript !== null) {
wscript.SendKeys("{F11}");
}
}
return true;
}
if (fullscreen){
fullscreen = cancelFullScreen(el);
}
else{
fullscreen = requestFullScreen(el);
}
}
MobileFullScreen = function ToggleFullScreen(el){
function cancelFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="";
return undefined;
}
function requestFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="#"+el+" {position:fixed;top:0px;left:0px;width:100%;height:100%;}";
return true;
}
if (fullscreen){
fullscreen = cancelFullScreen(el);
}
else{
fullscreen = requestFullScreen(el);
}
}
if( navigator.userAgent.match(/mobile/i)){
MobileFullScreen(el);
}
else{
DesktopFullScreen(el);
}
}
</script>
<style>
div{background:white;}
</style>
<style id="fullscreenstyle">
</style>
<div id="fullscreen" onclick="SetFullscreen(this.id)">hello</div>
Following on from your comments are you looking for something like this?
<script>
function cancelFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="";
selectedElement = document.getElementById(el);
selectedElement.setAttribute("onclick","requestFullScreen(this.id)");
document.body.innerHTML=bodysave;
return undefined;
}
function requestFullScreen(el) {
document.getElementById("fullscreenstyle").innerHTML="#"+el+" {background:pink;position:fixed;top:0px;left:0px;width:97%;height:97%;}";
selectedElement = document.getElementById(el);
bodysave = document.body.innerHTML;
while (document.body.firstChild) {
document.body.removeChild(document.body.firstChild);
}
document.body.appendChild(selectedElement);
selectedElement.setAttribute("onclick","cancelFullScreen(this.id)");
return true;
}
</script>
<style>
div{background:white;}
</style>
<style id="fullscreenstyle">
</style>
<div id="fullscreen" onclick="requestFullScreen(this.id)">hello</div>
<div id="fullscreen2" onclick="requestFullScreen(this.id)">hello</div>
<div id="fullscreen3" onclick="requestFullScreen(this.id)">hello</div>

Loop 3 images from my Div background-image Property

I have a code to loop images but based on an Img source, but how to improve it to make it work for the "background-image" property of a div?
HTML
<div id="section2"></div>
CSS
#section2 {
background-image: 'url(..images/banner1.jpg');
}
JAVASCRIPT
<script type = "text/javascript">
(function() {
var i = 1;
var pics = [ "images/banner1.jpg", "images/banner2.jpg", "images/banner3.jpg" ];
var el = document.getElementById('section2');
function toggle() {
el.src = pics[i];
i = (i + 1) % pics.length;
}
setInterval(toggle, 3000);
})();
</script>
Thanks in Advance :)
One way would be to use CSS classes instead of sources.
JS:
<script type = "text/javascript">
(function() {
var i = 1;
var classes = [ "bgd-1", "bgd-2", "bgd-3" ]; // adjusted
var el = document.getElementById('section2');
function toggle() {
el.className = classes[i]; // adjusted
i = (i + 1) % classes.length; // adjusted
}
setInterval(toggle, 3000);
})();
</script>
CSS:
#section2.bgd-1 {
background-image: url('..images/banner1.jpg');
}
#section2.bgd-2 {
background-image: url('..images/banner2.jpg');
}
#section2.bgd-3 {
background-image: url('..images/banner3.jpg');
}
Note:
Use el.className += ' ' + classes[i]; to append a class name instead of replacing all element classes.

Categories