Random Image selector from folder - javascript

I'm a student working on an art project in which I select one of 500 created images to show up on a webpage. I'm very new to coding and only really understand html and css, with very small amount of knowledge in JavaScript. I'm stuck in getting the images to show up, when I inspect it gives me an error saying: Failed to load resource: net::ERR_FILE_NOT_FOUND $selected_image}< I'm not really sure what to do with this, I hope someone would like to help me with this.
Thankyou :)
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" media="screen" href="css/main.css">
<!-- <link rel="JavaScript" href="script.js"> -->
<meta charset='utf-8'>
<meta content='IE=edge,chrome=1' http-equiv='X-UA-Compatible'>
<title>Mother</title>
<body>
<div id="container">
<div id="inner_container">
<img id="image_shower"/>
</div>
<div id="button_container">
<button onclick="get_random_image()"></button>
</div>
</div>
<script>
image_array = [
'Lilith10.png',
'Lilith11.png',
'Lilith12.png',
'Lilith13.png',
'Lilith14.png']
function get_random_image(){
random_index = Math.floor(Math.random() * image_array.lenght);
selected_image = image_array[random_index]
document.getElementById('image_shower').src = './images/$selected_image}'}
</script>
</body>
</html>

Javascript template strings are written with oblique quotes, and variables inside it must have brackets around them (you only had the closing one):
document.getElementById('image_shower').src = `./images/${selected_image}`;
EDIT
Even if in the present case this won't stop your code from working (unless you activate "strict mode"), I also recommend that you use the appropriate keywords to declare your variables.
const image_array = [
'Lilith10.png',
'Lilith11.png',
'Lilith12.png',
'Lilith13.png',
'Lilith14.png'
];
function get_random_image() {
const random_index = Math.floor(Math.random() * image_array.length);
const selected_image = image_array[random_index];
document.getElementById('image_shower').src = `./images/${selected_image}`;
}

Related

JavaScript setInterval animation creates gibberish without error in the console

I'm trying to create a simple animation with setInterval, and I'm testing it on a Python SimpleHTTPServer because I had some cross-origin issues earlier. There is no error in the console when I load the page, and I can see the loading overlay properly, and then the page just becomes gibberish (see images below) although the console shows it is loading image properly. I'm wondering what is wrong. Thanks!
(The gibberish is really long, so this screenshot is just part of it.)
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>fish</title>
<link rel="stylesheet" type="text/css" href="./assets/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id="overlay">
<img src="http://i.imgur.com/KUJoe.gif">
</div>
<div id="fish" style="width:100px; height:100px;"></div>
<script type="text/javascript">
$(window).on("load", function(){
$("#overlay").fadeOut();
var r = 1;
setInterval(function(){
if (r < 5) {
$("#fish").load("./assets/images/fish" + r + ".jpeg");
r++;
} else {
r = 1;
}
console.log(r);
console.log("./assets/images/fish" + r + ".jpeg");
}, 100);
});
</script>
</body>
</html>
When you say this:
$("#fish").load("./assets/images/fish" + r + ".jpeg");
...you are loading the data in the jpeg file as text within the #fish element - that is, you are doing the equivalent of trying to open a jpeg file in Notepad.
What you probably want to do is have an <img> element and set its src to that jpeg file - either change the <div> to be an <img> or add an <img> within the <div>:
<div style="width:100px; height:100px;"><img id="fish"></div>
// and then
$("#fish").prop("src", "./assets/images/fish" + r + ".jpeg");
Note that for smooth animation you probably want to "preload" all of the images, then use setInterval() after that to switch between them.

Calling .jSignature() on div doesn't update the div

I got this code from the GitHub:
<script src="path/to/jSignature.min.js"></script>
<script>
$(document).ready(function() {
$("#signature").jSignature()
})
</script>
<div id="signature"></div>
But it doesn't pull anything up on the actual webpage. I would think there is more code required but I don't know where to start.
Here is a minimal working example
<!DOCTYPE html>
<html lang="en">
<head>
<lang>
<title>Minimal working jSignature Example</title>
<meta charset="UTF-8">
<!-- Files from the origin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://willowsystems.github.io/jSignature/js/libs/jSignature.min.js"></script>
<head>
<script>
$(document).ready(function() {
// Initialize jSignature
$("#signature").jSignature();
})
// ripped from the description at their the Github page
function getBase64Sig(){
// get the element where the signature have been put
var $sigdiv = $("#signature");
// get a base64 URL for a SVG picture
var data = $sigdiv.jSignature("getData", "svgbase64");
// build the image...
var i = new Image();
i.src = "data:" + data[0] + "," + data[1];
// and put it somewhere where the sun shines brightly upon it.
$(i).appendTo($("#output"));
}
</script>
<body>
Put your signature here:
<div id="signature"></div>
<button onclick="getBase64Sig()">Get Base64</button>
<div id="output"></div>
</body>
</html>
I hope you can go on from here.
It is really as simple as they describe it to be, only their description of the actual example is a bit lacking for beginners.

What can't I get this random quote generator to work?

I've been trying to make a "Random Quote Machine" that randomly selects a quote from an array of 5 quotes and inserts the text into a paragraph on a webpage. The Machine uses HTML and JavaScript(jQuery). I suspect my error is pretty simple given how simple the project is.
Here's the HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
</body>
</html>
Here's the JavaScript:
var quotes = ["Innocence is thought charming because it offers delightful possibilities for exploitation.",
"Every day begins with an act of courage and hope: getting out of bed.",
"Hatred observes with more care than love does.",
"To understand someone, find out how he spends his money.",
"The educated do not share a common body of information, but a common state of mind."
];
function getQuote() {
return Math.floor(Math.random() * quotes.length);
}
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
Because your scripts are included in the head element, the quoteGen button doesn't exist in the DOM at the time that you try to bind an event handler to it. You need to either include the scripts just before the end of your body tag, or wrap your code in a DOM-ready event handler to ensure that the DOM exists as you expect it to when your code runs.
So, you could either go with this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Random Quote Machine</title>
</head>
<body>
<h1>Mason Cooley Quotes</h1>
<div>
<p id="quote"></p>
</div>
<button id="quoteGen">Generate A Random Quote</button>
<script src="jquery.min.js"></script>
<script src="quotes.js"></script>
</body>
</html>
... or, use a DOM-ready handler, such as this:
$(function () {
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
Works just fine?
http://jsfiddle.net/tj3dvz1m/.
make sure to run your code in a
$( document ).ready(function() {
Your code here.
});
The handler is being set before the #quoteGen dom node exists.
You need to move the inclusion of quotes.js to the end of your file, right before the closing of /BODY.
Or register the handler to be installed once the document is ready:
$(document).ready(function(){
$('#quoteGen').click(function() {
$('#quote').text(quotes[getQuote()]);
});
});
This code works fine. Credit to owner.
// Random Quotes
var Quotation=new Array()
Quotation[0] = "Time is of the essence! Comb your hair.";
Quotation[1] = "Sanity is a golden apple with no shoelaces.";
Quotation[2] = "Repent! The end is coming, $9.95 at Amazon.";
Quotation[3] = "Honesty blurts where deception sneezes.";
Quotation[4] = "Pastry satisfies where art is unavailable.";
Quotation[5] = "Delete not, lest you, too, be deleted.";
Quotation[6] = "O! Youth! What a pain in the backside.";
Quotation[7] = "Wishes are like goldfish with propellors.";
Quotation[8] = "Love the river's \"beauty\", but live on a hill.";
Quotation[9] = "Invention is the mother of too many useless toys.";
var Q = Quotation.length;
var whichQuotation=Math.round(Math.random()*(Q-1));
function showQuotation()
{document.write(Quotation[whichQuotation]);}
showQuotation();

Web-browser is not showing the output

I'm new to JavaScript and already encountered a problem. When I run the code and the browser pops up, it[browser] does not show anything. What I have is the testMethod.js file with one method:
function testMethod(num1, num2){
var value = num1 + num2;
return value;
}
and an HTML file from where I'm trying to run:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title> My JavaScript</title>
<script language = "javascript" src = testMethod.js"></script>
</head>
<body>
<script language = "javascript" type = "text/javascript">
// var getValue = testMethod(2,3);
document.write("The result is " + testMethod(5,3));
</script>
<noscript>
<h3> This site requires JavaScript</h3>
</noscript>
</body>
</html>
The code is not implementing the result at all. It shows only a blank page browser.
It seems you have a quote missing in the html, it should say src="testMethod.js" where you are including the script in the first place.

grid 960 - while executing inspectSection in dmx960 grid, js error occurred.

I'm trying to run this grid extention in DW CS5. I'm a front end person so debugging other people's code isn't my thing. So when I try set the grid precepts I get this error:
while executing inspectSection in dmx960 grid, js error occurred.
Here is the code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Barefoot Development Group</title>
<link href="CSS/Style.css" rel="stylesheet" type="text/css">
<link href="CSS/text.css" rel="stylesheet" type="text/css">
<link href="CSS/reset.css" rel="stylesheet" type="text/css">
</head>
<body>
<!------start container------->
<div id = "container" class ="container_16"></div>
<div id = "social_search" class = "grid_16"></div>
<div id = "social_links" class = "grid_1 alpha"></div>
<!------Main container-------->
<!------Header start---------->
<!------Social Links---------->
<!-------End social links------>
<!----start Social icons -------->
<!----end social icons----->
</body>
</html>
I tried deleting the cache in Config folder and reinstalling the extension. Didn't work. I checked the log files and found this:
JS Error: theElem.getAttribute is not a function filename:
C:\Users\cvr\AppData\Roaming\Adobe\Dreamweaver
CS5\en_US\Configuration\Shared\DMXzone\960 Grid\dmx960grid_lib.js
lineno: 598
So I went to the JS file and here is what I found in this expression block:
function getGridClassNum(theElem) {
if (!theElem) return 0;
var cls = theElem.getAttribute("class");
if (!cls) return 0;
if (cls == 'clearfix') {
//Try to read the parent
var parent = getGridElement(theElem.parentNode);
if (parent && parent.nodeType === Node.ELEMENT_NODE) {
return getGridClassNum(parent);
}
} else {
var numMatch = cls.match(new RegExp("\\b(grid|container)_(\\d+)\\b"));
if (numMatch && numMatch.length > 1) {
return parseFloat(numMatch[2]);
// //decrease with prefix and suffix
// - getGridClassNameNum(theElem, 'prefix')
// - getGridClassNameNum(theElem, 'suffix');
}
}
return 0;
}
I don't see anything particularly amiss here. But perhaps a more expert debugger can tell me if there is something going on here. Here is what confuses me - I was looking for the function inspectSection but I couldn't find it. I'm left scratching my head here.
Could this be a problem of including the script directly into the html doc?
Thanks!

Categories

Resources