Trying to load random images using jquery -- Not working - javascript

I'm brand new to javascript and jquery. I'd like to load a random image when I load the page. I found some code that looked really easy, but I can't seem to make it work and I don't know what I'm doing wrong. Everything looks good to me....
My HTML is below:
<html xmlns="http://www.23.org/19999/xhtml">
<head>
<title>A Site Just For Me!</title>
<script type="text/javascript" src="jquery.min.js"></script>
<link href='http://fonts.googleapis.com/css?family=Economica:400,700|Francois+One' rel='stylesheet' type='text/css'>
<script type="text/javascript" src="myjs.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap-theme.min.css">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="me_css.css">
</head>
<body >
<div class="jumbotron">
<div class="container">
<div class="greeting"></div>
<div id="happypic"></div>
<div id="banner"></div>
<div id="banner2"></div>
</div>
</div>
</body>
</html>
Here's my javascript file:
// A $( document ).ready() block.
$( document ).ready(function() {
});
//This is where i set up my greeting.
var nowDate=new Date();
var nowHour=nowDate.getHours();
var greeting;
if (nowHour<11)
{
//good morning
greeting="Good morning";
}
else if (nowHour<16)
{
//good afternoon
greeting="Good afternoon";
}
else
{
//good evening
greeting="Good evening";
}
//document.write("<center><h1>"+greeting+", Loser!");//
// This is where i put my random picture chooser
// pictures
//random image experiment
var hawaiiPix=new Array("hawaii1.jpg", "hawaii2.jpg", "hawaii3.jpg", "hawaii4.jpg", "hawaii5.jpg");
$('<img src="img/'+hawaiiPix[Math.floor(Math.random()*hawaiiPix.length)]+'">"').appendTo('#happypic');
var images = ["hawaii1.jpg", "hawaii2.jpg", "hawaii3.jpg", "hawaii4.jpg", "hawaii5.jpg"];
$('<img src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#banner');
$('<h1>Hello</h1>').appendTo('#banner2');
Any insight would be much appreciated...

The problem is that your jQuery code is outside the ready function, so it is running before the DOM has been loaded, so it cannot add the image because those elements don't exists in the HTML page yet.
One way is to put the loading of your myjs.js file before </body> so when it executes the items are loaded (you'll need to remove the jQuery.ready code) or you can put it inside the ready block like this:
$( document ).ready(function() {
//This is where i set up my greeting.
var nowDate=new Date();
var nowHour=nowDate.getHours();
var greeting;
if (nowHour<11)
{
//good morning
greeting="Good morning";
}
else if (nowHour<16)
{
//good afternoon
greeting="Good afternoon";
}
else
{
//good evening
greeting="Good evening";
}
//document.write("<center><h1>"+greeting+", Loser!");//
// This is where i put my random picture chooser
// pictures
//random image experiment
var hawaiiPix=new Array("hawaii1.jpg", "hawaii2.jpg", "hawaii3.jpg", "hawaii4.jpg", "hawaii5.jpg");
$('<img src="img/'+hawaiiPix[Math.floor(Math.random()*hawaiiPix.length)]+'">"').appendTo('#happypic');
var images = ["hawaii1.jpg", "hawaii2.jpg", "hawaii3.jpg", "hawaii4.jpg", "hawaii5.jpg"];
$('<img src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#banner');
$('<h1>Hello</h1>').appendTo('#banner2');
});
The best way is to move the loading of jQuery and your JS file at the bottom of the html code.

Related

Captain.speak() method issue

I am currently learning about objects within class. I created an object with constructor notation in Javascript, and instantiated four different objects with distinct names. For some reason, when I try to run the Captain.speak() method in my code, it doesn't work. It should display the Captain.strPhase string that I created right before initiating the command for the function. When I check this in online compilers, there are no errors, but it doesn't output my string. Would anyone happen to know why?
$(document).ready(function() {
function Pirate(rank, phrase, id) {
output = "";
randNum = 1;
secretNum = 1;
this.strRank = rank;
this.intNum = favnum;
this.strPhrase = phrase;
this.elOutput = document.getElementById(id);
this.speak = function() {
this.elOutput.innerHTML += "<br>" + this.strPhrase;
}; //End speak
this.chooseRandNum = function() {
this.randNum = Math.floor(Math.random() * 10);
}; //End chooseRandNum
}; //End Pirate
var Captain = new Pirate("Captain", "", "captain");
var firstMate = new Pirate("First Mate", "I love guessing games!", "pirate1");
var Quartermaster = new Pirate("Quartermaster", "This game should be fun.", "pirate2");
var Gunner = new Pirate("Gunner", "Let's start playing!", "pirate3");
Captain.strPhrase = "Argh maties, ready to play a guessing game?";
Captain.speak();
}); // end of $(document).ready()
<html lang="en">
<head>
<meta charset="utf-8">
<!-- Begin every html page with everything up to this point (just use your own header block) -->
<!-- Also, feel free to remove all the instructional comments as you modify this file to make it yours. -->
<!-- This <title> displays in the page tab -->
<title>Randomness</title>
<!-- This will link to your CSS stylesheet for formatting as soon as you create the file. The page will work without it, though. -->
<link rel="stylesheet" href="css/myFancyStylesheet.css">
<!-- This links to the jQuery library so your js code will work
Always include this *before* your own js code (extremely important) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- This links to the js code specific for this page -->
<script src="Randomness.js"></script>
</head>
<body>
Captain's Guessing Game:
<br></br>
<div id="captain">
</div>
<br></br>
<div id="pirate1">
</div>
<br></br>
<div id="pirate2">
</div>
<br></br>
<div id="pirate3">
</div>
</body>
</html>
When I run your code, I get an error message:
Uncaught ReferenceError: favnum is not defined
If you comment out this line...
// this.intNum = favnum;
...everything should work just fine.

How can I change default backround color of botman.io widget

Im using botman.io package for chatboot widget.
Everything works perfectly but problem is that i can't change default background color of chat widget. On inspect console it shown that boman widget calls ( https://cdn.jsdelivr.net/npm/botman-web-widget#0.0.20/build/assets/css/chat.css ) link, but i cant find that call on my localhost project. If anyone know solution i would appreciate.
<script src="{{ asset('/js/webflow.js') }}"></script>
<script>
var botmanWidget = {
title:'Scarletbot',
introMessage: 'Hello, I am a Scarlet! I am here to assist you and answer all your questions about our products and services!',
mainColor:'#c02026',
aboutText:'',
bubbleBackground:'#c02026',
headerTextColor: '#fff',
};
</script>
<script id="botmanWidget" src="{{ asset('/js/widget.js') }}"></script>
You may add frameEndpoint in
var botmanWidget = {
frameEndpoint: '<?php echo base_url('botdemo/chatserver1');?>',
title:'Scarletbot',
introMessage: 'Hello, I am a Scarlet! I am here to assist you and answer all your questions about our products and services!',
mainColor:'#c02026',
aboutText:'',
bubbleBackground:'#c02026',
headerTextColor: '#fff',
};
frameEndpoint is nothing but source of iframe loaded by botman-widget
frameEndpoint source is like :
<!doctype html>
<html>
<head>
<title>BotMan Widget</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/assets/css/chat.min.css">
</head>
<body>
<script id="botmanWidget" src='https://cdn.jsdelivr.net/npm/botman-web-widget#0/build/js/chat.js'></script>
</body>
</html>
Here you may use own css as well.
I quickly checked out the web widget on the botman github.
There is a simple link to the chat.css in the head of chat.html located in the src folder.
This points to assets/css/chat.css, which you can edit freely and add a background-color to.
I use brute force in the iframe to change background with jquery
$(document).on('click', '.desktop-closed-message-avatar img', function() {
var iframe = document.getElementById("chatBotManFrame");
iframe.addEventListener('load', function () {
var htmlFrame = this.contentWindow.document.getElementsByTagName("html")[0];
var bodyFrame = this.contentWindow.document.getElementsByTagName("body")[0];
var headFrame = this.contentWindow.document.getElementsByTagName("head")[0];
var image = "https://images.unsplash.com/photo-1501597301489-8b75b675ba0a?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1349&q=80"
htmlFrame.style.backgroundImage = "url("+image+")";
bodyFrame.style.backgroundImage = "url("+image+")";
});
});

Rotating Images with JavaScript

I realise this is all over the internet, but I can't actually find one that I know how to use. I'm very new to JS, and still pretty new to HTML. The most useful thing I've found is this, except I don't know how to actually implement it into my code. Based on something else I found, I tried this.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="Styling/style.css">
<script language="JavaScript">
var image = document.getElementById("img1");
var src = ["concert2.gif", "concert3.gif", "concert4.gif", "concert5.gif", "concert1.gif"];
</script>
</head>
<body>
<img id="img1" src="concert1.gif" alt="concert1.gif">
<script language="JavaScript">
var step = 0
function slideit() {
image.src = src[step];
image.alt = src[step];
if (step < 4) {
step++;
} else {
step = 1;
}
}
setInterval(slideit, 5000);
</script>
</body>
It didn't work, it just stayed at concert1.gif. Some help would really be appreciated!
-Thanks
The error is that you are trying to retrieve image element before it's loaded in the first script tag. Also language='javascript' is no longer required as JavaScript is now the only scripting language.
Here is your code:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="Styling/style.css">
</head>
<body>
<img id="img1" src="concert1.gif" alt="concert1.gif">
<script>
var image = document.getElementById("img1");
var src = ["concert2.gif", "concert3.gif", "concert4.gif", "concert5.gif", "concert1.gif"];
var step = 0
function slideit() {
image.src = src[step];
image.alt = src[step];
if (step < 4) {
step++;
} else {
step = 1;
}
}
setInterval(slideit, 5000);
</script>
</body>
It still doesn't show up anything because maybe your src is not correct. But, you can still see alt attribute changing. LoL ;)

How to create a simple Loading CSS that shows "loading" right at the first time the page got loaded & clear it after the page finished loading?

I am using Java script with GWTP technology to build my app.
Ok, I have a requirement. I want to use loading CSS to show the loading information right at the first time the page got loaded. The loading must show before any javascript files begin to be downloaded.
After all javascript files got downloaded, the loading CSS should stop working.
For example, when people visit mydomain.com, it should show "..loading..." indicator in the middle of the page & after the page starts to be visible, then it should hide the loading indicator.
The structure of my Ajax page is as following.
<html>
<head>
<meta>...</meta>
<link type="text/css" rel="stylesheet" href="myCss.css">
<script type="text/javascript" language="javascript" src="myproject.nocache.js"> </script> // this is where the big Javascript file got loaded
</head>
<body>
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position: absolute; width: 0;height: 0; border: 0;"></iframe>
</body>
</html>
Can you not just use the "onload" attribute of the body tag?
Put this javascript line to make the "loading" disappear at the end of the large javascript file :
document.getElementById('loading').className='loaded';
<!DOCTYPE HTML>
<html>
<head>
<meta>...</meta>
<link type="text/css" rel="stylesheet" href="myCss.css">
</head>
<script>
function pageLoaded(){
var jsFile=document.createElement('script');
jsFile.setAttribute("type","text/javascript");
jsFile.setAttribute("src", 'myproject.nocache.js');
document.getElementsByTagName("head")[0].appendChild(jsFile);
}
</script>
<style>
html{width:100%;height:100%;}
body{width:100%;height:100%;margin:0px;position:relative;}
div#loading{display:table;width:100%;height:100%;position:absolute;top:0px;left:0px;}
div#loading div{display:table-cell;width:100%;height:100%;text-align:center;vertical-align:middle;background-color:#cccccc;}
div.loaded#loading{display:none;}
</style>
<body onload="pageLoaded();">
<div id="loading">
<div>LOADING...</div>
</div>
<iframe src="javascript:''" id="__gwt_historyFrame" tabIndex='-1' style="position: absolute; width: 0;height: 0; border: 0;"></iframe>
</body>
</html>
Add loading class to body in the HTML code
<body class="no-mobile pc bootstrap loading">
And when all loading of scripts finished remove the loading class of body tag.
window.onload = function () {
$("#body").removeClass('loading');
}
This is just example, You can use pure javascript to remove 'loading' class of body.
Like this
Used body as ID, because I can't put custom body tag there.
(function (w, d, url, resource) {
w.t = new Date().getTime();
if (/webkit/i.test(w.navigator.userAgent)) {
d.write("<style>#loading"
+ "{-webkit-animation:blink"
+ " 350ms linear 0s normal infinite forwards;}"
+ "#-webkit-keyframes blink{"
+ "0%{color:transparent;}100%{color:blue;}};"
+ "</style>");
};
d.write("<div id=loading"
+ " style=font-size:24px;position:relative;"
+ "left:45%;top:25%;-moz-text-blink:blink;>"
+ "loading...</div>");
var script = d.createElement("script");
script.src = url;
script.async = true;
script.type = "text/javascript";
var head = d.getElementsByTagName("head")[0];
head.appendChild(script);
w.s = setInterval(function () {
// check for `object` or `function`, i.e.g., `window.jQuery()`
// set by `script` (`src`), `url`, resource at `window`,
// at `1000ms` intervals , adjustable, e.g., `500`; `250`
if (resource in w
&& typeof w.jQuery() === "object"
&& typeof w.jQuery === "function" ) {
// do stuff
d.body.removeChild(d.getElementById("loading"));
d.write("<span class=status>jQuery version: "
+ jQuery().jquery
+ "\n"
+ "estimated loading time: "
+ Number(new Date().getTime() - w.t)
+ "</span>");
// do stuff
// utilize `object`, `function`, data
// loaded in `window`, `document`,
// from `script`, `url` , resource
$("body")
.append("<br><iframe "
+ "src=http://api.jquery.com "
+ "width=480 height=400></iframe>");
$(".status").fadeOut(5000, function() {
$(".status", this).remove();
});
clearInterval(w.s);
};
}, 1000);
}(window, document, "http://code.jquery.com/jquery-latest.js", "jQuery"));
jsfiddle http://jsfiddle.net/guest271314/27RTx/

Edit html div that has been copied into html file with jquery load

So I have a website with a Header.html. In the header are three buttons. I've copied the Header.html into all of my other pages with jquery's load. Now what I would like to do is change the colour of one of the buttons depending on the page it's on. But when I use document.GetElementById in javascript it can't find the div of the button I've copied from the Header.html
Here's the Header.html
<div id="Header_Wrapper">
<div id="Header_PageLinksWrapper">
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_Games" href="..\Pages\Games.html">Games</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_AboutMe" href="..\Pages\AboutMe.html">About Me</a>
</div>
<div class="Header_PageLink">
<a class="Header_PageLinkText" id="PageLink_CV" href="..\Pages\CV.html">CV</a>
</div>
</div>
</div>
The javascript file:
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html");
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
}
);
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = document.getElementById(id);
if (divElement == null)
{
console.log("Could not find element " + id);
}
divElement.style.color = 0xffffff;
}
One of the pages (eg. Games.html)
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Adabelle Combrink - Games</title>
<link rel="stylesheet" type="text/css" href="..\Templates\Header.css"/>
<link rel="stylesheet" type="text/css" href="..\Templates\Page.css"/>
<link rel="stylesheet" type="text/css" href="..\Pages\Games.css"/>
<script type="text/javascript" src="..\Scripts\jQuery.js"></script>
<script type="text/javascript" src="..\Scripts\Defaults.js"></script>
</head>
<body>
<header>
<div id="Header"></div>
</header>
</body>
</html>
What this gives me in the console is Could not find element PageLink_Games. I don't get that error if I use something that is in Games.html like Header.
Is there any other way of doing the same thing. I know you can include files into eachother with php but I haven't gotten that right and don't seem to be able to run .php files in Visual Studio.
jQuery.load has a success callback. Use it to assure your code is only executed after the loading is complete.
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", null, function() {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);
Also your SetPageLinkColours function can be improved with jQuery:
function SetPageLinkColours(aPath)
{
var firstIndex = aPath.lastIndexOf("/");
var lastIndex = aPath.indexOf(".html");
var id = "PageLink_" + aPath.slice(firstIndex + 1, lastIndex);
var divElement = $("#"+id);
if (!divElement.length)
{
console.log("Could not find element " + id);
}
else
{
divElement.css('color','white');
}
}
load function makes async request , so your code tries to find element before it rely appears. U need to use load function callback http://api.jquery.com/load/
$(document).ready(
function ()
{
$("#Header").load("..\\Templates\\Header.html", function () {
var filePath = window.location.pathname;
SetPageLinkColours(filePath);
});
}
);

Categories