How to change background image with static css and maintain it? - javascript

I have a question about background image change in MVC.
I have a main css for the website, multiple webpages within the website and i have a webpage within the user profile to change the background image of the website.
I have set up 4 pictures on a row with function. I also have typed in a javascript prior to the images div, e.g in the top of
My problem is that when i run the page. the images wont change background when i click on the images. Thus I can change the background by image click if i go to inspect element and turn of background-image of my "Site.css" ( my main webpage css, ill throw in a gyazo here: http://gyazo.com/169070689792884090f1d9a9c9b96158).
Seems like the Site.css is static or something. Bootstrap is used on the website, also a masterpage is created, could that be a missing point from my pov.
also, how would I save the image to remain background on all pages afterwards?`
here is my cshtml code for image backgrounds:
#{
ViewBag.Title = "Javascript - Change Background";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>#ViewBag.Title.</h2>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="ButtonChangeBackground.css">
</head>
<body>
<script language="JavaScript">
var backImage = new Array();
backImage[0] = "/Content/img/Wood_floor_by_gnrbishop.jpg";
backImage[1] = "/Content/img/blue_wave_of_water-wide.jpg";
backImage[2] = "/Content/img/Falling-asleep-forest.jpg";
backImage[3] = "/Content/img/lava.jpg";
function changeBGImage(whichImage) {
if (document.body) {
document.body.background = backImage[whichImage];
}
}
</script>
<div id="choosebg">
<button onclick="javascript: changeBGImage(0);"><img id="wood" style="width: 100px; height: 80px;" src="~/Content/img/Wood_floor_by_gnrbishop.jpg" alt="" /></button>
<button onclick="javascript: changeBGImage(1);"><img id="water" style="width: 100px; height: 80px;" src="~/Content/img/blue_wave_of_water-wide.jpg" alt="" /></button>
<button onclick="javascript: changeBGImage(2);"><img id="forest" style="width: 100px; height: 80px;" src="~/Content/img/Falling-asleep-forest.jpg" alt="" /></button>
<button onclick="javascript: changeBGImage(3);"><img id="lava" style="width: 100px; height: 80px;" src="~/Content/img/lava.jpg" alt="" /></button>
</div>
<p> <div class="btn btn-default col-md-offset-2 "> #Html.ActionLink("Back to Profile", "Details") </div>
</p>
</body>
</html>

try this
...
function changeBGImage(whichImage) {
if (document.body) {
document.body.style.backgroundImage = 'url(' + backImage[whichImage] + ')';
}
}
...

Related

Opening and closing pictures with single buttons (JavaScript)

I am new to JavaScript. I created this code in order to try and make buttons that will hide
and show certain pictures on the page. I have 3 buttons, the first of which is supposed to run my JavaScript code in <script></script> tags, the other two just have Javascript code inside them and they work fine. But they don't hide the picture once they are clicked a second time, which is why I am trying to do that for the first one if possible.
For some reason, I cannot get the first button with "open()" to work the way I want with my Javascript code. Can anyone with more experience please explain to me what I am doing wrong? Thank you in advance...
var btn1 = document.getElementById('1');
var btn2 = document.getElementById('2');
var btn3 = document.getElementById('3');
var display1 = btn1.getAttribute('display')
var display2 = btn2.getAttribute('display')
var display3 = btn3.getAttribute('display')
function open() {
if (display1 === ('none')) {
btn1.setAttribute('display', 'block');
} else {
btn1.setAttribute('display', 'none');
}
}
<img id="1" src="forge.PNG" style="height:320px; display:none; padding:10px">
<img id="2" src="lizard.jpg" style="height:320px; display:none; padding:10px">
<img id="3" src="walkway.jpg" style="height:320px; display:none; padding:10px">
<button onclick="open()">1</button>
<button onclick="document.getElementById('2').style.display='block'">2</button>
<button onclick="document.getElementById('3').style.display='block'">3</button>
I'd use event delegation to watch for clicks on the container. When the nth button is clicked, select the nth image, and toggle a class that hides/shows the image:
const images = document.querySelectorAll('img');
const buttons = [...document.querySelectorAll('button')];
document.addEventListener('click', (e) => {
if (e.target.matches('button')) {
const i = buttons.indexOf(e.target);
images[i].classList.toggle('hidden');
}
});
.hidden {
display: none;
}
<img id="1" src="https://www.gravatar.com/avatar/34932d3e923ffad9a4a1423e30b1d9fc?s=48&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="2" src="https://www.gravatar.com/avatar/978ec0c47934c4b04401a8f4b4fec8bd?s=32&d=identicon&r=PG&f=1" style="height:320px; padding:10px" class="hidden">
<img id="3" src="https://lh3.googleusercontent.com/-uIr21N5ccCk/AAAAAAAAAAI/AAAAAAAAHeg/ohNEkpJKXQA/photo.jpg?sz=32" style="height:320px; padding:10px" class="hidden">
<button>1</button>
<button>2</button>
<button>3</button>
Problems with your original code include:
You're trying to select the elements before they exist in the DOM
Elements do not have a display property - in order to check the style of an element, you have to access its .style property first (eg, someImage.style.display)
Similarly, to set the style of an element, you have to set a property of its style property (eg someImage.style.display = <newDisplay>). Setting the display attribute of the element won't do anything.
Try to avoid inline handlers if at all possible - they have many problems and are pretty much universally considered to be quite poor practice. Always attach listeners properly using Javascript instead, whenever that's an option.
The event listener is the better solution, but if you want to see a working code in your way:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>switchpics</title>
</head>
<script type="text/javascript">
var open = function(param) {
img = document.getElementById(param.innerHTML);
if (img.style.display == 'none'){
img.style.display = "block";
} else {
img.style.display = "none";
};
};
</script>
<body>
<img id="1" src="1.jpg" style="height:20px; display:block; padding:10px">
<img id="2" src="1.jpg" style="height:20px; display:none; padding:10px">
<img id="3" src="1.jpg" style="height:20px; display:none; padding:10px">
<button onclick="open(this)">1</button>
<button onclick="open(this)">2</button>
<button onclick="open(this)">3</button>
</body>
</html>

load gif until page is fully load

I want to display a gif image until the website is completely loaded.
Once I click button (onclick=window.open) a new page opened but is blank and the gif is only appearing once the website is loaded.
I want once clicking the button a new page opened and showing immediately the gif and disappear once the page is loaded
Can anyone help me, what I’m doing wrong or what is missing to load the gif when the page is loading? Here is my code, thank you so much
land.php file:
<button type="button"
onClick="window.open('./gremo.cfm ',
toolbar=no,
menubar=no,
scrolling=yes,
scrollbars=yes
')">
</button>
gremo.php file:
<head>
<script type="text/javascript">
function showHide(elementid){
if (document.getElementById(elementid).style.display == 'none'){
document.getElementById(elementid).style.display = '';
} else {
document.getElementById(elementid).style.display = 'none';
}
}
window.onload = function () { reSizeTextarea(); showHide('loadingd'); }
</script>
</head>
<body>
<div id="loadingd" align="center">
<br/><br/><br/><img src="./loading.gif">
</div>
</body>
Note that when you are running locally, resources are loading fast.. very fast
Don't forget to use your developer tools and configure network throttling (to simulate a slower connection). That should simulate a "real" scenario and let you test your code better
Here is a screenshot from chrome... enjoy!
When you have a lot of content, it will take time to load. The image will show and than hide when the onload event happens. Now run it again, the content is cached and loading will take no time at all.
So load time depends on what there is to load/render, how it is loaded, and if it is cached or not.
window.onload = function () {
document.getElementById("loading").remove()
document.querySelector(".content").removeAttribute("hidden")
}
[hidden] {
display: none
}
#loading {
width: 300px;
}
<img id="loading" src="https://media.giphy.com/media/3o7bu8sRnYpTOG1p8k/source.gif" />
<div class="content" hidden>
<img src="http://placekitten.com/200/200" />
<img src="http://placekitten.com/100/100" />
<img src="http://placekitten.com/300/300" />
<img src="http://placekitten.com/400/400" />
<img src="http://placekitten.com/500/500" />
</div>
In your example, you have nothing that takes time to load other than the loading image. So as soon as your image is loaded, the window.onload is triggered. That is why it flashes.
If you want the image to show, you can add some logic saying if I have not been here for X seconds, than wait....
var startTime = new Date()
window.onload = function () {
var loadTime = new Date()
var diff = loadTime - startTime;
if (diff > 5000) {
toggleLoad()
} else {
window.setTimeout(toggleLoad, 5000 - diff)
}
}
function toggleLoad () {
document.getElementById("loading").remove()
document.querySelector(".content").removeAttribute("hidden")
}
[hidden] {
display: none
}
#loading {
width: 300px;
}
<img id="loading" src="https://media.giphy.com/media/3o7bu8sRnYpTOG1p8k/source.gif" />
<div class="content" hidden>
<img src="http://placekitten.com/200/200" />
<img src="http://placekitten.com/100/100" />
<img src="http://placekitten.com/300/300" />
<img src="http://placekitten.com/400/400" />
<img src="http://placekitten.com/500/500" />
</div>
To ensure the loading gif loads fast, on the parent page, you probably want to preload it
var img = new Image()
img.src = "your.gif"

Looping images in div element

I'm a beginner starting to learn coding. I have designed an neuroscience related experiment on a webpage with 4 layers of webpage. my first layer will be constant. Second layer shows different images during each round of questioning. Third and fourth layer are questions displayed at certain time intervals and/or on click of submit. I would like to know how do i display the different images every time. Precisely, Can i do it using a for loop!?
<html>
<head>
<Title> Experiment </title>
<link rel="stylesheet" type="text/css" href="displayfieldset.css">
</head>
<body>
<!-- Layer 1 of cross hair image -->
<div id="crosshair" style="background-color:black; position:absolute; width:100%; height:100%; z-index:1; align:center">
<img src="crosshair.jpg" width="1350px" height="750px" >
</div> <!-- Layer 1 closed -->
<!-- Layer 2 of Images -->
<div id="piclayer" style="position:absolute ;width:98%; height:98%; z- index:2; align:center; margin-left:0.5%; margin-top:0.5%">
<img id="images" src="image1.jpg" style="width:1325px; height:720px; display:none">
</div> <!-- Layer 2 closed -->
<!-- Layer 3 Question 1 -->
<div id="questionone" style="z-index:3; position:absolute; display:none; margin-left: 180px">
<fieldset name="field1_1" id="field1_1">
<form name ="problem1_1" id="problem1_1" >
<b> Identify the problem shown in this image. </b>
<br>
<br>
<input type="text" name="answer1_1" id="answer1_1" maxlength="30" style="width: 400px">
<br>
<br>
<input type="button" value="Submit" onclick="showdiv()" >
</form>
</fieldset>
</div>
<!-- Layer 4 Question 2 -->
<div id="questiontwo" style=" position: absolute; z-index:5; align:center; display:none; margin-left: 180px">
<fieldset name="field1_2" id="field1_2" style="position:relative; align:center">
<form name ="problem1_2" id="problem1_2" >
<b> Propose a solution to the problem. </b>
<br>
<br>
<input type="text" name="solution1_2" id="solution1_2" maxlength="30" style="height: 200px; width: 400px">
<br>
<br>
<br>
<input type="button" value="Submit" onclick="hidediv()" >
</form>
</fieldset>
</div>
<script>
function showdiv()
{
document.getElementById('questiontwo').style.display = "block";
document.getElementById('questionone').style.display = "none";
}
function hidediv()
{
document.getElementById('piclayer').style.display = 'none';
document.getElementById('questionone').style.display = 'none';
document.getElementById('questiontwo').style.display = 'none';
}
<!-- Time out for image -->
setTimeout
( function()
{
document.getElementById('images').style.display = 'block';
}
,6000
);
<!-- Timeout for first question -->
setTimeout
( function()
{
document.getElementById('questionone').style.display = 'block';
}
,12000
);
</script>
</body>
</html>
Based on your coding,
The "crosshair" image, layer-1 is show always at z-index:1.
Layer-2 images will show after 6 seconds of page load at z-index:2.
Layer-3 div will show after 12 seconds of page load at z-index:3.
In the Layer-3, there is a submit button. If user click on the Submit button,
Layer-4 will be display and Layer-3 will be hide.
There is a submit button inside Layer-4 again, if user click on that button, all images will be hidden.
So, what you want to do?
Do you want to show images from Layer-2 by looping? If yes, here is sample codes:
var x = 0;
function myFunction(){
var Layer2Images = document.querySelectorAll("img.images");
if (x == Layer2Images.length)
x=0;
for (i = 0; i < Layer2Images.length; i++) {
Layer2Images[i].style.display = 'none';
}
Layer2Images[x].style.display = 'block';
x++;
}
setInterval(myFunction, 1000)
<!-- Layer 2 of Images -->
<div id="piclayer" style="position:absolute ;width:98%; height:98%; z-index:2; align:center; margin-left:0.5%; margin-top:0.5%">
<img class="images" src="https://pixabay.com/static/uploads/photo/2012/05/29/00/43/car-49278_1280.jpg" style="width:400px;height:300px; display:none;">
<img class="images" src="https://static.pexels.com/photos/24353/pexels-photo-large.jpg" style="width:400px; height:300px; display:none;">
<img class="images" src="https://static.pexels.com/photos/16155/pexels-photo-large.jpg" style="width:400px; height:300px; display:none;">
</div> <!-- Layer 2 closed -->
Check out document.querySelector and document.querySelectorAll. With those you can target a single DOM node by CSS query selector or you can target multiple DOM all at once and then loop over them in a for of loop by converting the nodes to an array with Array.from.
Full working example
let i = 0
// Grab all the layers and read them into an array so we can iterate them.
let layers = Array.from(document.querySelectorAll('img.layer'))
const nextLayer = () => {
// increment i and compare incremented value, if greater than 3, reset to first layer.
if(++i > 3)
i = 1
// iterate all layers and set their CSS display property to none.
layers.forEach((x) => { x.style.display = 'none' })
// select the single layer we are currently on and set its css display to block.
document.querySelector(`img.layer_${i}`).style.display = 'block'
}
// show first layer
nextLayer()
// show next layer every 2 seconds
setInterval(nextLayer, 2000)
<img class="layer layer_1" src="http://www.jqueryscript.net/images/Simplest-Responsive-jQuery-Image-Lightbox-Plugin-simple-lightbox.jpg" />
<img class="layer layer_2" src="http://cdn.theatlantic.com/assets/media/img/photo/2015/11/images-from-the-2016-sony-world-pho/s01_130921474920553591/main_900.jpg" />
<img class="layer layer_3" src="http://livewallpaper.info/wp-content/uploads/2015/12/Desktop-Cute-Wallpapers-HD-1920x1080-1.jpg" />

Getting blank page sent to printer using a hidden div method

I am using a code snippet that I found to display a multipage form using visibility hidden.
There is a very good possibility that all of my problem stems from this method. That resource was from here:
http://www.devx.com/webdev/Article/10483/0/page/2
It is a fairly straightforward way to display multiple pages of a form...it probably was never intended to be able to allow printing.
<html>
<head>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script language="JavaScript">
$.getScript("printThis.js", function(){
});
var currentLayer = 'page1';
function showLayer(lyr){
hideLayer(currentLayer);
document.getElementById(lyr).style.visibility = 'visible';
currentLayer = lyr;
}
function hideLayer(lyr){
document.getElementById(lyr).style.visibility = 'hidden';
}
function showValues(form){
var values = '';
var len = form.length - 1; //Leave off Submit Button
for(i=0; i<len; i++){
if(form[i].id.indexOf("C")!=-1||form[i].id.indexOf("B")!=-1)
continue;
values += form[i].id;
values += ': ';
values += form[i].value;
values += '\n';
}
alert(values);
}
</script>
<style>
body{
font: 10pt sans-serif;
}
.page{
position: absolute;
top: 10;
left: 100;
visibility: hidden;
}
</style>
</head>
<body>
<form id="multiForm" action="App1.php" method="POST" action="javascript:void(0)" onSubmit="showValues(this)" id="app">
<div id="page1" class="page" style="visibility:visible;">
Applicant Name: <input type="text" size="50" name="name1" >
</form>
<p><input type="button" id="C1" value="Continue" onClick="showLayer('page2')"></p>
</div>
<div id="page2" class="page">
This is Page 2
<br>
<input type="button" id="B1" value="Go Back" onClick="showLayer('page1')">
<input type="button" id="B2" value="Print App" onClick="$('#page1').printThis({})">
<br><br>
</div>
</form>
</body>
</html>
The "Print App" button is properly calling the printThis plugin. However, I get no content from the page1 DIV section. All that is printed is the normal header portion (Page 1 of 1) in the upper right and about:blank in lower left and date in lower right of page…no content, which with my sample file should be Applicant Name input box.
I assume that this is because the DIV for page1 is set to "hidden" while the content of page2 is being displayed. If I substitute "page2" in the button call then I get the content from page2 as expected.
So...I guess what I am after is a way to temporarily change the DIV being referenced in the printThis button call to be visible just long enough to perform the page print.
Any ideas?
I'm the plugin author - you need to incorporate the print media query into your css.
This would also help users that select file > print or control + P, as it will show all form elements.
The print media query allows you to make styling changes specifically for the printed page.
Example:
#media print {
#page1, #page2 {
display: block;
visibility: visible;
position: relative;
}
}
You include this in your css.
Additionally, based on your above code - you have css and javascript inline in your page. You should consider moving both to an external files, for maintenance and improved code standards.
printThis won't work with your current setup, because the plugin looks for the container (selector) you have specified and any linked css in the head of the document.
So for the above, you can do the following:
<!-- move all of this to the bottom of the page for performance -->
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script type="text/javascript" src="printThis.js"></script>
<script type="text/javascript" src="myJavascript.js"></script>
<!-- the above file is your javascript externalized, remove $.getScript, wrap in $(document).ready() -->
Then put this in your head:
<link type='text/css' rel='stylesheet' href='style.css'>
<!-- contains your css from the page, including the print media query -->

Get image src from a image in a slideshow

I've been looking around much today and spend a few hours trying to get something done. For a client I am creating a slideshow with a lightbox when clicked on an image. The slideshow and lightbox both work, but I don't get the right image in the lightbox yet.
This is the code that loads the slideshow and when clicked on an image opens the lightbox.
(The images for the slideshow get loaded by a php script and turned into a Javascript array)
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
}
</script>
<div style="width: 170px; height: 160px">
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style. display='block'">
<img id="slideshow" src="" />
</a>
<div id="light" class="white_content">
<img id="lightImg" src="" />
<script>
var image = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", image);
</script>
I now try to create a variable named "image"and let this contain the src of the current image in the slideshow. So I can load this to the image in the lightbox.
Hopefully some one can give me some usefull tips. I am pretty new in the Javascript language.
The script for the slideshow came from: http://www.javascriptkit.com/javatutors/externalphp2.shtml
Regards Koen.
These days there really is no excuse for using obtrusive Javascript (Stuff inside your HTML attributes, ideally it should be in an external file. http://en.wikipedia.org/wiki/Unobtrusive_JavaScript).
I have done you the favour of cleaning up your code a bit, and changed it where you seemed to be going wrong. As DotNetter has already pointed out it would be sensible to use jQuery in this instance, as it really does simplify things. However, I'm going to assume that for some reason you want it in plain js. Below is a simplification of the code that you posted with the correct change.
<style type="text/css">
.wrapper {
width: 170px;
height: 160px;
}
</style>
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/" + galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
document.getElementById("slideshow").onclick = function () {
var imageSrc = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", imageSrc);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
}
</script>
<div class='wrapper'>
<img id="slideshow" src="" />
<div id="light" class="white_content">
<img id="lightImg" src="" />
</div>
</div>
Before, you were getting the src of the current image when the page loaded, you need to be getting the src of the image when the user clicks on the

Categories