Javascript not running nearlyfreespeech - javascript

I set up an e-commerce website for a friend using javascript and html, and with the nearlyfreespeech hosting service. I have made sure to load the html page correctly, and there are no errors (in both the console and on the actual page). I have also tried with both the javascript embedded in the html, and with 2 seperate files, but neither works. I am using no external libraries either. I added alerts for when the page loads, but nothing showed up. The page constructor is hooked up to the page via the onload event set on the body tag. I have tried it with Firefox, Google Chrome, and Internet Explorer, but neither worked. When I moved the creation of the controls into the html, the controls were there (meaning that the html is working), but the alerts still didn't show (signifying that the javascript is either being omitted or that the onload event is not being fired). Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<title>GetLost</title>
<script type="text/javascript">
function loadcontrols()
{
var items = ["Green cuff", "Red cuff"];
var prices = ["20.00", "30.00"];
var colors = ["Green", "Red"];
var urls = ["http://media-cache-ak0.pinimg.com/736x/0f/f8/11/0ff811addad9b0165263eb73ba9806f0.jpg", "http://www.opalona.com/images/produits/big/big_2049-3.jpg"];
var controls = [];
for(var i = 0; i < items.length; i++)
{
var item = new loaditem(items[i], prices[i], colors[i], urls[i]);
controls.concat(item);
}
alert("All items loaded.")
}
function loaditem(name, value, color, imageUrl)
{
this.name = name;
this.value = value;
this.color = color;
this.imageUrl = imageUrl;
var container = document.CreateElement("div");
container.style.height = "300px";
container.style.width = "200px";
container.style.backgroundColor = color;
scroller.appendChild(container);
var image = document.CreateElement("img");
image.style.height = "220px";
image.style.witdh = "180px";
image.setAttribute("src", imageUrl);
container.appendChild(image);
var name = document.CreateElement("h4");
name.innerHTML = name + " for $" + value;
container.appendChild(name);
alert("The product " + name + "has been loaded.")
}
</script>
</head>
<body onload="loadcontrols">
<h1><b>Choose a product, and click on it to open it.</b></h1>
<div style="overflow-x: scroll" name="scroller" height="310px" width="650px"></div>
</body>
</html>

onload doesn’t take a function name; it takes some JavaScript code to run. If you had a single line of JavaScript code just referencing a variable:
loadcontrols
Then, well, nothing happens. If you want to call it, you need parentheses:
loadcontrols()

Related

Is there a way to switch images src back to original after on.click src change event?

I'm a noob working my way to learn JavaScript on my own and using some resources but want to probe things on my own hence trying this thing but it's not working for some reason. Help is appreciated.
The object is to clarify some blurred images by swapping the source. The images are called zero.jpg/zeroblur.jpg, one.jpg/oneblur.jpg and so on... The page loads with blurred image sources until clicked on. I want to write code so that it goes back to original blurred source image after 5 secs.
P.S.: The code in comments is what I've tried to write on my own.
window.onload = init;
function init() {
var blurryPic = document.getElementsByTagName("img");
for (var i = 0; i < blurryPic.length; i++) {
blurryPic[i].onclick = clarify;
// setTimeout(resetPic, 5000);
}
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
}
// function resetPic(eventObj) {
// var pic = eventObj.target;
// var id = pic.id;
// id = "images/" + id + "blur.jpg";
// pic.src = id;
// }
It's better with CSS: your image stays the same and you only toggle a class, the class making your image blur.
document.getElementById("clickImg").addEventListener("click", function() {
this.classList.toggle("blurImg")
})
.blurImg {
-webkit-filter: blur(5px); /* Safari 6.0 - 9.0 */
filter: blur(5px);
}
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
If what you want is really to be able to reset the original image, I think it's better to stock it in a specific attribute, like this:
document.getElementById("reset").addEventListener("click", function() {
document.getElementById("clickImg").src = document.getElementById("clickImg").getAttribute('origSrc')
})
var imgs = [
'https://vignette.wikia.nocookie.net/spongebob/images/d/d7/SpongeBob_stock_art.png/revision/latest?cb=20190921125147',
'https://static.vecteezy.com/system/resources/previews/000/072/351/non_2x/spongebob-squarepants-vector.jpg',
'https://upload.wikimedia.org/wikipedia/en/c/c7/BattleForBikiniBottom.jpg'
]
document.getElementById("random").addEventListener("click", function() {
document.getElementById("clickImg").src = imgs[Math.floor(Math.random() * 3)]
})
<input type="button" value="RESET" id="reset" />
<input type="button" value="RANDOM" id="random" /><br/>
<img src="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" origSrc="https://www.muralsticker.com/23751-thickbox/autocollants-en-vinyle-pour-enfants-spongebob-squarepants.jpg" id="clickImg">
I used an if statement for this to check if the first loaded image file was present or not. Then use the attribute src for the file. Here's an example.
#javascript
function magicChanger(){
var myImage = document.getElementById("emailImage")
if (myImage.getAttribute("src") == "first loaded image"){
myImage.setAttribute("src", "second image")
}
else{
myImage.setAttribute("src", "first loaded image")
}
}
#html element
<button id = "emailButton" onclick="magicChanger()">
<img id="emailImage" src="{% static 'GoEnigmaPics/emailIcon.png' %}" alt="email">
</button>
Thanks for all the answers! I wanted to get it done in JS only so CSS wouldn't work. Appreciate the answers and will definitely incorporate in future projects!
P. S. This is what got it done in the end.
window.onload = init;
function init() {
var blurryPics = document.getElementsByTagName("img");
for (var i = 0; i < blurryPics.length; i++) {
blurryPics[i].onclick = clarify;
}
function clarify(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + ".jpg";
pic.src = id;
setTimeout(reBlur, 3000, pic);
}
function reBlur(eventObj) {
var pic = eventObj.target;
var id = pic.id;
id = "images/" + id + "blur.jpg";
pic.src = id;
}
Please try this code,To Is there a way to switch images src back to original after on.click src change event?
It switches back because by default, when you click a link, it follows the link and loads the page. In your case, you don't want that. You can prevent it either by doing e.preventDefault();
$(function() {
$('.menulink').click(function(){
$("#bg").attr('src',"img/picture1.jpg");
return false;
});
});
I hope this code will be useful.
Thank You.

Why do I get null when I getElementById?

I'm new to JS, and reading Javascript Dom, I'm trying to figure out one of the example in my book!
here is my html code
<!DOCTYPE html>
<html lang ="en">
<head>
<meta charset="utf-8" />
<title>Image Gallery</title>
</head>
<body>
<script type = "text/javascript" src="showPic.js"></script>
<h1>Snapshots</h1>
<ul id = "image">
<li>
Fall
</li>
<li>
Sunshine
</li>
<li>
Green
</li>
<li>
Filter
</li>
</ul>
<img id = "placeholeder" src="images/rise.jpg" alt = "my image gallery"/>
<p id="description"> Choose an image</p>
</body>
</html>
here is my javaScript code
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholeder");
placeholder.setAttribute("src", source);
description.firstChild.nodeValue = text;
}
var text = whichPic.getAttribute("title");
var description = document.getElementById("description");
function perpareGallery() {
var gallery = document.getElementById("image");
var links = gallery.getElementsByTagName("a");
for(var i = 0 ; i<links.length; i++) {
links[i].onclick = function() {
showPic(this);
return false;
}
}
}
my code didnt getting anything from id = image. and I checked many times dont know what is wrong....
There seems to be no code that actually runs the perpareGallery() function.
After you fix that, it might still not work if you run perpareGallery() before the elements in HTML (like your a elements) are parsed and rendered. So, you might want to do something like:
window.onload = prepareGalery;
Although there are way better ways to set-up events, this will run your function after all HTML is parsed.
Two advices on how to track down your issue:
1) All browsers have a so called javascript console. It shows you all syntax error with your code. For firefox and chromium the keyboard shortcut F12 turns it on/off
If you run your code and open the javascript console you'll see this error:
ReferenceError: whichPic is not defined
In your example it looks as if the line var text = whichPic.getAttribute("title"); belongs to the function showPic(whichPic), but it doesn't.
2) You should format your code to not get lost. Your current code formatted:
function showPic(whichPic) {
var source = whichPic.getAttribute("href");
var placeholder = document.getElementById("placeholeder");
placeholder.setAttribute("src", source);
description.firstChild.nodeValue = text;
}
var text = whichPic.getAttribute("title");
var description = document.getElementById("description");
function perpareGallery() {
var gallery = document.getElementById("image");
var links = gallery.getElementsByTagName("a");
for(var i = 0 ; i<links.length; i++) {
links[i].onclick = function() {
showPic(this);
return false;
}
}
}
If you now take a look to the formatted code, it no longer looks as if whichPic is used inside of showPic(whichPic) but outside of the scope. The error makes perfectly sense.
You might want to move it inside of the function, before you use it.

How to pass a variable in document.getElementById. As well as getting undefined when calling a value in an array

<iframe id="frmFile" src="Book1.txt" onload="generateInventory();" style="display: none;"></iframe>
<script>
function csvpls() {
var oFrame = document.getElementById("frmFile");
var strRawContents = oFrame.contentWindow.document.body.childNodes[0].innerHTML;
while (strRawContents.indexOf("\r") >= 0)
strRawContents = strRawContents.replace("\r", "");
var arrLines = strRawContents.split(",");
return arrLines
}
function generateInventory(a, b) {
var xx = csvpls()
var div = document.createElement("div");
div.style.width = "1000px";
div.style.height = "100px";
div.style.background = "red";
div.style.color = "white";
div.innerHTML = "Hello " + xx[a] + " yes!";
document.getElementById(b).appendChild(div);
}
</script>
<div id="Q1"></div>
<script>
generateInventory(20, Q1);</script>
</body>
I am trying to create edit multiple divs with the following code. I hope to call each function with parameters to create the divs and put content in them.
So I have some problems with the code above. First off, document.getElementById(str).appendChild(div); is not working the way I want it to. It works if I put the div id "Q1" instead of b. Just wondering, if I can pass a variable through it. Secondly, when I change the div to "Q1", the div is generated, but the content in there is "Hello undefined Yes". If I call the array with xx[20] instead of xx[a], I would get what I want which is "Hello content yes". Sorry, this probably seems like a nuisance, any help is appreciated.

Appending to body with javascript

I have an assignment to make several bugs fly around the screen randomly, but I'm having problems getting divs to be added to the html body through javascript.
<head>
<title>Fly little bug! Fly!</title>
<script type="text/javascript">
/* <![CDATA[ */
var numBugs = 0;
var body = document.getElementsByTagName("body");
function bug(startX, startY, xSpeed, ySpeed){
var self = this;
this.xPos = startX;
this.yPos = startY;
this.xSpeed = xSpeed;
this.ySpeed = ySpeed;
this.divId = "bug" + numBugs;
this.div = document.createElement("div");
this.div.innerHTML = "test";
body.appendChild(self.div);
this.fly = function(){
self.xPos += self.xSpeed;
self.yPos += self.ySpeed;
}
this.fly();
this.flyInterval = setInterval(function(){ self.fly(); },5000);
numBugs++;
}
/* ]]> */
</script>
</head>
<body onload = "var bug1 = new bug(10, 20, 5, 3);">
</body>
</html>
I can see two problems.
The getElementsByTagName function returns an array of elements. You have to be explicit that you want the first element of the array.
var body = document.getElementsByTagName("body")[0];
You're essentially saying "give me all the tags in the document of type 'body'". It gives you a list of tags, and you have to get the first one even though there should only be one "body" in any HTML document. The [0] in the code above gives you the first one.
You are trying to access the body before it's created. The <script> occurs in the document before the <body> tag, so at the time the script is executed, the body doesn't exist. You need to move the call to getElementsByTagName inside the bug() function.
document.body.innerHTML += '<div>Div Content</div>';
Look into jQuery if you want to make simple DOM manipulation easier on yourself.

Smilie system: Event to add image in textarea fails

I'm trying to create a personalized smilies system to train my JavaScript.
To accomplish that I have an offline system to save the various user smilies (I only save the urls).
After obtaining the data I try to make them appear above the textarea I want. So far so good!
Now, the problem comes when it's time to add the events to the images.
I try to add event listeners to each image but no matter which image I press only the last image event is triggered.
This is: all images appear side by side correctly but what is inserted in the textarea is the last image that is iterated in the cycle.
Meaningful code:
/* Insert the code in the right place in the textarea*/
function putInTxtarea(text, textarea) {
// Mozilla text range replace.
if (typeof(textarea.selectionStart) != "undefined") {
var begin = textarea.value.substr(0, textarea.selectionStart);
var end = textarea.value.substr(textarea.selectionEnd);
var scrollPos = textarea.scrollTop;
textarea.value = begin + text + end;
if (textarea.setSelectionRange)
{
textarea.focus();
textarea.setSelectionRange(begin.length + text.length, begin.length + text.length);
}
textarea.scrollTop = scrollPos;
}
// Just put it on the end.
else {
textarea.value += text;
textarea.focus(textarea.value.length - 1);
}
var elem = document.createElement("div");
elem.id = "mySmilies";
elem.innerHTML = "";
for each (url in smiliesUrl){
var img = document.createElement("img");
img.src = url;
img.style.cursor = "pointer";
img.addEventListener('click',
function(){putInTxtarea('[img]'+url+'[/img]', document.getElementsByName('message')[0]);
};, false); // here is the event attaching
elem.appendChild(img);
}
Don't use for each...in. This is a construct only available in Firefox (at least it is non-standard).
You are making the typical creating-a-function-in-a-loop mistake. JavaScript has only function scope. Every function you create in the loop has references to the same variables (url in your case) and this variable will have the value of the last URL after the loop finished. You need to introduce a new scope:
function createClickHandler(url) {
var target = document.getElementsByName('message')[0];
return function() {
putInTxtarea('[img]'+url+'[/img]', target);
}
}
// assuming smiliesUrl is an array
for(var i = smiliesUrl.length;i--;) {
var url = smiliesUrl[i];
var img = document.createElement("img");
img.src = url;
img.style.cursor = "pointer";
img.addEventListener('click', createClickHandler(url), false);
elem.appendChild(img);
}
Another possible is to simply access the image from the event handler. It should available via this:
img.addEventListener('click', function(){
putInTxtarea('[img]'+this.src+'[/img]',
document.getElementsByName('message')[0]);
};, false);
This seams to be a closure issue. the variable url points to the url used in the loop, and at the time of execution it is always be the last url.
for(url in smiliesUrl){
var img = document.createElement("img");
img.src = url;
img.style.cursor = "pointer";
var func = function(jUrl){
return function(){
putInTxtarea('[img]' + jUrl + '[/img]',
document.getElementsByName('message')[0]);
};
}(url);
img.addEventListener('click', func, false);
}
For more on closures in javascript see This question

Categories

Resources