I am new to JavaScript and I do not know how to approach this homework assignment -
"modify the page to hide all the images until the “start” button is clicked. Once clicked the start button should become the stop button and display the word “stop” and when clicked hide the images. Once hidden that same button should become the start button and display the word “start” and act again like the start button. Notice there is a single button that changes the text and what is does depending on whether the show is currently stopped or started."
I know i am supposed to use the show/hide effects, but I don't really know how to apply them to the code?
<!doctype html>
<html>
<head>
<title>Slide Show</title>
<!-- will remove the 404 error for favicon.ico from console -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<!-- using jQuery -->
<link href="simpleImageV2.css" rel="stylesheet" type="text/css">
<script src="jquery-3.3.1.min.js"></script>
<script src="simpleImagesV2.js"></script>
</head>
<body bgcolor="black" onload="preLoadImages()">
<div id="setSize">
<img name="campus_pic" src="images/fall_1_480x640.png" width="480" height="640">
</div>
<br />
<br />
<button id="startShow">Start the Show</button>
<button id="stopShow">Stop the Show</button>
</body>
</html>
JavaScript -
/*global $ */
var i = 0, myTimer, campus;
function preLoadImages() {
"use strict";
if (document.images) {
campus = new Array(); // global variable
campus[0] = new Image();
campus[0][0] = "images/fall_1_480x640.png";
campus[0][1] = "480";
campus[0][2] = "640";
campus[1] = new Image();
campus[1][0] = "images/winter_1_640x480.png";
campus[1][1] = "640";
campus[1][2] = "480";
campus[2] = new Image();
campus[2][0] = "images/spring_1_640x480.png";
campus[2][1] = "640";
campus[2][2] = "480";
campus[3] = new Image();
campus[3][0] = "images/summer_1_480x640.png";
campus[3][1] = "480";
campus[3][2] = "640";
} else {
window.alert("This browser does not support images");
}
}
You can use jQuery for that like below :
/*global $ */
var i = 0, myTimer, campus;
function preLoadImages() {
"use strict";
if (document.images) {
campus = new Array(); // global variable
campus[0] = new Image();
campus[0][0] = "images/fall_1_480x640.png";
campus[0][1] = "480";
campus[0][2] = "640";
campus[1] = new Image();
campus[1][0] = "images/winter_1_640x480.png";
campus[1][1] = "640";
campus[1][2] = "480";
campus[2] = new Image();
campus[2][0] = "images/spring_1_640x480.png";
campus[2][1] = "640";
campus[2][2] = "480";
campus[3] = new Image();
campus[3][0] = "images/summer_1_480x640.png";
campus[3][1] = "480";
campus[3][2] = "640";
} else {
window.alert("This browser does not support images");
}
}
function init() {
$('#stopShow').hide();
}
$(document).ready(function () {
$("#startShow").click(function () {
var images = ['<div>'];
campus.forEach(function (img) {
images.push('<img src="' + img[0] +'" height="' + img[1] + '" width="' + img[2] + '" />');
});
images.push('</div>');
$("#images").html(images.join(''));
$('#startShow').hide();
$('#stopShow').show();
});
$("#stopShow").click(function () {
$("#images").html('');
$('#stopShow').hide();
$('#startShow').show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<title>Slide Show</title>
<!-- will remove the 404 error for favicon.ico from console -->
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon">
<link rel="icon" href="favicon.ico" type="image/x-icon">
<!-- using jQuery -->
<link href="simpleImageV2.css" rel="stylesheet" type="text/css">
<script src="jquery-3.3.1.min.js"></script>
<script src="simpleImagesV2.js"></script>
</head>
<body bgcolor="black" onload="preLoadImages(); init();">
<div id="setSize">
<img name="campus_pic" src="images/fall_1_480x640.png" width="480" height="640">
</div>
<br />
<br />
<div id="images"></div>
<button id="startShow">Start the Show</button>
<button id="stopShow">Stop the Show</button>
</body>
</html>
Related
I have this simple snippet. Only thing it does is to refresh the content after the user touches one of the buttons:
<html>
<head>
<title>Title</title>
<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style-2.css">
<link rel="stylesheet" type="text/css" href="responsive.css">
<script>
function init() {
var content = "";
var rand;
for(var i=0; i<5; i++)
{
rand = Math.floor(Math.random() * 10);
content += "<a class=\"button\" id=\"" + rand + "\" onClick=\"init();\" href=\"#!\">" + rand + "</a>\n";
}
document.getElementById("choices").innerHTML = content;
}
function refreshcontent()
{
setTimeout(function(){ init()}, 900);
}
</script>
<meta charset="UTF-8">
</head>
<body>
<main>
<body onload = "init();"/>
<section id="services" class="white" >
<div id = "choices" >
</div>
</section>
</main>
</body>
</html>
In Android, PC, and Mac, it works fine. But in my iPhone, regardless of the browser I use, the button I touch stays "pressed" after the content reloads.
I tested it by touching to a button and then immeadiately touching some empty space on screen, then it works fine.
What am I missing?
I'm trying to shrink an image based off of what I learned on the mobile app SoloLearn. Please help.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css"/>
</head>
<body>
<img id="image" src="myImage.jpg"/>
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.style.width = 50;
img.syle.height = 25;
};
</script>
</body>
</html>
Rather then using img.style just set the width and height values of the image.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css" />
</head>
<body>
<img id="image" src="http://www.placehold.it/150" />
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.width = 50;
img.height = 25;
};
</script>
</body>
</html>
The width and height styles aren't numbers, they need units as well, like px for pixels. So
function shrnk() {
img.style.width = '50px';
img.style.height = '25px';
}
The only time you can omit the units is when you're setting them to 0, since that's the same regardless of the units.
If you'd like to use the style property you need to set the unit of the number you're talking about (ie. "px").
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="xyz.css" />
</head>
<body>
<img id="image" src="http://lorempixel.com/200/200" />
<button id="shrink">Shrink</button>
<script>
var x = document.getElementById('shrink');
var img = document.getElementById('image');
x.addEventListener("click", shrnk);
function shrnk() {
img.style.width = "50px";
img.style.height = "25px";
};
</script>
</body>
</html>
I have the following html page which displays a picture at a random location and updates it every 10 seconds :
<!DOCTYPE html>
<html>
<head>
<title>Domoos | Screen saver screen</title>
<meta http-equiv="refresh" content="10">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
<meta http-equiv="pragma" content="no-cache">
<link rel="stylesheet" type="text/css" href="css/mystyle_saver.css" />
<script type="text/javascript" src="scripts/date_time.js"></script>
<script type="text/javascript">
function init() {
var xmin = 0;
var xmax = 890;
var ymin = 0;
var ymax = 430;
var xCoord = Math.floor((Math.random()*xmax)+xmin);
var yCoord = Math.floor((Math.random()*ymax)+ymin);
var xCoordStr = xCoord.toString() + "px";
var yCoordStr = yCoord.toString() + "px";
document.getElementById("randomPlacement").style.left = xCoordStr;
document.getElementById("randomPlacement").style.top = yCoordStr;
}
</script>
</head>
<body onload="init();">
<div style="position:absolute" id="randomPlacement">
<p><img src="assets/pictures/texte_sortie_veille.png" alt ="" style="width:60px;height:60px;"></p>
</div>
</body>
</html>
It works very well. Now, I would like to add two 'div' tags so I could display the date and the time. So, I updated the body tag as follows (the rest of the page remains unchanged) :
<body onload="init();">
<div style="position:absolute" id="randomPlacement">
<p><img src="assets/pictures/texte_sortie_veille.png" alt ="" style="width:60px;height:60px;"></p>
</div>
<div id="date">
<script type="text/javascript">window.onload = getDate('date');</script>
</div>
<div id="time">
<script type="text/javascript">window.onload = getTime('time');</script>
</div>
</body>
The problem by doing so is that the image is never displayed at a random location. What am I missing and hopefully how can I solve the issue? I have added an extract of the console in Chrome.
Thanks a lot for your help.
replace
<div id="date">
<script type="text/javascript">window.onload = getDate('date');</script>
</div>
<div id="time">
<script type="text/javascript">window.onload = getTime('time');</script>
</div>
with
<div id="time">
</div>
then in init()
function init() {
var xmin = 0;
var xmax = 890;
var ymin = 0;
var ymax = 430;
var xCoord = Math.floor((Math.random()*xmax)+xmin);
var yCoord = Math.floor((Math.random()*ymax)+ymin);
var xCoordStr = xCoord.toString() + "px";
var yCoordStr = yCoord.toString() + "px";
document.getElementById("randomPlacement").style.left = xCoordStr;
document.getElementById("randomPlacement").style.top = yCoordStr;
document.getElementById("date").innerhtml=getDate('date');
document.getElementById("time").innerhtml=gettime('time');
}
I am stuck on my homework project. I am supposed to create a JavaScript program that shows an animated puppy running. I must use caching to start the animation as soon as the images finish loading and 1 of the following: getElementsByName(), getElementById(), or getElementsByTagName(). Here's what I have so far but when I run it in Firefox all I see is a flashing box that says "image of a puppy"
<!DOCTYPE HTML>
<html>
<head>
<title>Running Puppy</title>
<meta http-equiv="content-type" content="text/html;
charset=utf-8" />
<script type="text/javascript">
/* <![CDATA[ */
var puppy = new Array(6);
var curPuppy = 0
for (var imagesLoaded=0; imagesLoaded < 6;
++imagesLoaded) {
puppy[imagesLoaded] = new Image();
puppy[imagesLoaded].src
= "images/puppy" + imagesLoaded + ".gif";
}
function run(){
if (curPuppy == 5)
curPuppy = 0;
else
++curPuppy;
document.getElementById("puppyImage").src = puppy[curPuppy].src;
}
/*]]> */
</script>
</head>
<body onload="setInterval('run()', 150)">
<img src="images/puppy0.gif" id="puppyImage" width="263" height="175" alt="Image of a puppy." />
<script type="text/javascript">
/* <![CDATA[ */
document.write("<h1 id='mainHeading'></h1>");
document.getElementById("mainHeading").innerHTML = document.getElementsByTagName("title")[0].innerHTML;
/*]]> */
</script>
</body>
</html>
For image upload in a cakephp project I used java-script.I added this js file in app\View\Layouts default.ctp
js code
document.querySelector('input[type=file]').addEventListener('change', function(event){
var files = event.target.files;
for (var i = 0; i < files.length; i++) {
if (files[i].type.match(/image.*/)) {
var reader = new FileReader();
reader.onload = function (readerEvent) {
var image = new Image();
image.onload = function (imageEvent) {
var imageElement = document.createElement('div');
imageElement.classList.add('uploading');
imageElement.innerHTML = '<span class="progress"><span></span></span>';
var progressElement = imageElement.querySelector('span.progress span');
progressElement.style.width = 0;
document.querySelector('form div.photos').appendChild(imageElement);
var canvas = document.createElement('canvas'),
max_size = 1200,
width = image.width,
height = image.height;
if (width > height) {
if (width > max_size) {
height *= max_size / width;
width = max_size;
}
} else {
if (height > max_size) {
width *= max_size / height;
height = max_size;
}
}
canvas.width = width;
canvas.height = height;
canvas.getContext('2d').drawImage(image, 0, 0, width, height);
var xhr = new XMLHttpRequest();
if (xhr.upload) {
// Update progress
xhr.upload.addEventListener('progress', function(event) {
var percent = parseInt(event.loaded / event.total * 100);
progressElement.style.width = percent+'%';
}, false);
xhr.onreadystatechange = function(event) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
imageElement.classList.remove('uploading');
imageElement.classList.add('uploaded');
imageElement.style.backgroundImage = 'url('+xhr.responseText+')';
console.log('Image uploaded: '+xhr.responseText);
} else {
imageElement.parentNode.removeChild(imageElement);
}
}
}
xhr.open('post', 'process.php', true);
xhr.send(canvas.toDataURL('image/jpeg'));
}
}
image.src = readerEvent.target.result;
}
reader.readAsDataURL(files[i]);
}
}
event.target.value = '';
I have checked there are no problem.
now in add.ctp file I adder
<input type="file" multiple />
In output I am seeing the file type field.Now when I clicked on this field and upload a image then mojila bug given me a error.That is
document.querySelector(...) is null error
I have no idea about this error.In here why saying queryselector is null?
document.querySelector() behaves similarly to the jQuery.(document).ready() method. When the DOM is ready, the selector returns the object.
I would suggest you call all JS script bottom of the page.
To make sure that your DOM is ready you could add this to your JS file.
// my-script.js
document.addEventListener("DOMContentLoaded", function() {
// this function runs when the DOM is ready, i.e. when the document has been parsed
document.querySelector('input[type=file]')
.addEventListener('change', function(event){
...
}
});
This way you could call your js files from wherever you like. Please take a look to this superb answer to get further insight on these matters.
Also take a look at this other Google rule.
file.js
const heading1 = document.querySelector(".heading1");
console.log(heading1);
Solution 1
Use defer (best & recommended way):
<!DOCTYPE html>
<html lang="en">
<head>
<script src="./file.js" defer></script>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
</body>
</html>
Solution 2
Place your JavaScript in bottom before closing body tag
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<h1 class="heading1">Hello World 1</h1>
<script src="./file.js"></script>
</body>
</html>
I suggest writing your <script type="text/javascript" src="your js file"></script> in body, before the closing tag
There is now another "better" way to address this issue.
put your scripts in the head tag and add the defer attribute.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<script src="main.js" defer></script>
</head>
<body>
yoyoyo
</body>
</html>
you can read more about it here and here
TLDR (may be inaccurate and misleading so read the sources above!):
the defer attribute tells the browser to load the file but hold off its execution until the dom is ready, which is close to the behavior you implicitly get when you put the script tag at the bottom of the body tag, the difference being that in the old way you have to wait for the whole body tag to be parsed until you start downloading the script tag.
I ran into this issue where I was trying to do (slimmed down for simplicity):
<script type="text/javascript">
var svg = document.querySelector('svg');
console.log(svg);
</script>
on an element in the <body>:
<svg id="svg" viewBox="0 0 120 120" width="500px" height="500px"></svg>
Once I added jQuery and moved my lines inside of a $(document).ready(), it was fine:
<script type="text/javascript" src="jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var svg = document.querySelector('svg');
console.log(svg);
});
</script>
Here's a quick fix. I was trying to effect some changes in my HTML page using DOM and was getting this error. The problem was I linked my Javascript file inside the head tag of the HTML page, when I changed that and linked it at the body just before the closing body tag, it worked!
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Soft dog</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#3.4.1/dist/css/bootstrap.min.css"
integrity="sha384-HSMxcRTRxnN+Bdg0JdbxYKrThecOKuH5zCYotlSAcp1+c8xmyTe9GYg1l9a69psu" crossorigin="anonymous">
<link rel="stylesheet" href="landing.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link
href="https://fonts.googleapis.com/css2?family=Cormorant+SC:wght#300&family=Edu+VIC+WA+NT+Beginner&display=swap"
rel="stylesheet">
</head>
<body>
<div class="container">
<h2 id="newBrand">Welcome to SOFTDOG</h2>
<p><em>property of soft 6</em></p>
<a id="ceo" href="home.html"><img src="softdogmerch1.jpg" alt="check network"></a>
<p id="enterstatement">Please<a href="home.html">
<P><span>ENTER HERE</span></P>
</a><span>to feed your eyes and fill your wardrobe</span>
</p>
<label for="emailinput">email:</label>
<input id="emailinput" type="email" name="useremail" placeholder="user#email.com" required>
<label for="passwordinput">password:</label>
<input id="passwordinput" type="password" name="userpassword" placeholder="" required>
<input id="clickme" type="submit" name="login" value="log in">
<input id="clickme" type="submit" name="signup" value="sign up">
</div>
<script src="landing.js"></script>
</body>
</html>