Giving an onclick function to a link - javascript

I'm messing around with JavaScript and I want to have a coloured square with 3 links and depending on the link I click, the square will change colours. I can't get it to work and I'm not sure where I went wrong..
index.html
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test Page 2</title>
<script src="switch.js" type='text/javascript'></script>
</head>
<body>
<img id='square' src="img/blue.png"><br>
<a href="#" id='blue'>Blue!</a>
<a href='#' id='red'>Red!</a>
<a href='#' id='green'>Green!</a>
</body>
</html>
switch.js
var switch = (function() {
var red = document.body.getElementById('red');
var square = document.body.getElementById('square');
red.onclick = function() {
square.src = 'img/red.png';
}
})();

You're running your code before the elements exist.
Move the <script> element to the bottom of the <body> (so that it runs after they exist), or run the code in the load event.

You have two issues.
First you are using a variable called switch, that is a no no. Switch is a reserved word because it is a switch statement. Rename it.
var xswitch = (function() {
Second, It is because you are runnnig the code before the element exists on the page. It needs to be executed onload, document dom loaded [ready], or the script needs to be added at the bottom of the page.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test Page 2</title>
</head>
<body>
<img id='square' src="img/blue.png"><br>
<a href="#" id='blue'>Blue!</a>
<a href='#' id='red'>Red!</a>
<a href='#' id='green'>Green!</a>
<script src="switch.js" type='text/javascript'></script>
</body>
</html>

Make the following changes in order to ensure that the DOM has loaded.
HTML
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Test Page 2</title>
<script src="switch.js" type='text/javascript'></script>
<script type="text/javascript">
window.onload = function () {
switchFn();
};
</script>
</head>
<body>
<img id='square' src="img/blue.png"><br>
<a href="#" id='blue'>Blue!</a>
<a href='#' id='red'>Red!</a>
<a href='#' id='green'>Green!</a>
</body>
</html>
JavaScript (switch.js)
var switchFn = function () {
var red = document.getElementById('red');
var square = document.getElementById('square');
red.onclick = function () {
square.src = 'img/red.png';
}
};

Related

translate is not a function (in 'translate()', 'translate' is true)

I am trying to make a simple latin dictionary. I am new to JavaScript so I am trying to test the input tag with the alert function. In the console, I am receiving the error message after I click the "translate" button. Error: "translate is not a function (in 'translate()', 'translate' is true)".
HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Latin Dictionary</title>
</head>
<h1 id="main-header">Latin Dictionary!</h1>
<body>
<input id="latin-word" placeholder="Latin to English"/>
<br />
<button onclick="translate()" id="btn-translate-latin-english">Translate</button>
<script type="text/javascript" src="translate.js"></script>
</body>
</html>
JavaScript:
function translate() {
var latinWord = document.getElementById("latin-word").value;
alert("word that was entered: " + latinWord);
}
Thank you in advance :)
To solve it, choose another function name, such as myTranslate().
Why you can't use translate()? Because there's already a built-in translate in HTML. See here.
Note: You can choose whatever you want.
JS Code:
function myTranslate() {
var latinWord = document.getElementById("latin-word").value;
alert("word that was entered: " + latinWord);
}
HTML:
<button onclick="myTranslate()" id="btn-translate-latin-english">Translate</button>
Let me know if it works.
I think this error is being called because you are using the script tag after the button tag. I think moving the script into the head of the html will solve the issue
You seem to use the function's name translate which is a reserved word in JavaScript.
translate is a global attribute to make elements translatable or movable.
You must rename the function to fix this error. I used Translate():
function Translate() {
var latinWord = document.getElementById("latin-word").value;
alert("Word that was entered: " + latinWord);
}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css">
<title>Latin Dictionary</title>
</head>
<h1 id="main-header">Latin Dictionary!</h1>
<body>
<input id="latin-word" placeholder="Latin to English"/>
<br />
<button onclick="Translate()" id="btn-translate-latin-english">Translate</button>
<script type="text/javascript" src="translate.js"></script>
</body>
</html>

Javascript preserving a URL parameter on page change

I'm using Vanilla Javascript,
I have two pages, page01.html and page02.html these pages share the same navigation system.
I want to load a parameter into the url of page01, and after I click page02 on navigation, page02 will load with the parameter within its URL.
example:
I'm on page01.html
I load a param into the URL, so now I have page01.html/?param=X
I click the menu item page02
I want to load page02.html/?param=X
Is there any way to do this without using localStorage and sessionStorage?
Here's a simple solution using vanilla JavaScript:
Page01.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>Page 1</div>
go to page 2
<script>
var linkToPage2 = document.querySelector("a[href='page02.html']");
linkToPage2.addEventListener("click", function(e){
e.preventDefault();
if(location.search){
window.location.href = "page02.html" + location.search;
}
});
</script>
</body>
</html>
Page02.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<div>Page 2</div>
go to page 1
<script>
var linkToPage1 = document.querySelector("a[href='page01.html']");
linkToPage1.addEventListener("click", function(e){
e.preventDefault();
if(location.search){
window.location.href = "page01.html" + location.search;
}
});
</script>
</body>
</html>
I used both Bergi's comment and Henry's answer to create my own version.
Basically I just created a onclick="menuClick();" and an id="menuLink" on the a tag.
Then on the Javascript I just added the location.search to the href:
menuClick = function() {
document.getElementById('menuLink').href += location.search
}

Global variables are undefined in new pop up window, while they were defined beforehand

I tried to create two buttons, so that when I click on each- I will get a pop up small window, with a content that it will get while onloading.
This is the code:
index.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="script.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
</head>
<body ng-app="myApp">
<p ng-controller="ctrl">
<span ng-repeat="x in items">
<button ng-click="parentFunc(x.fieldOne,x.fieldTwo)">{{x.fieldOne}}</button>
<br><br>
</span>
</p>
<script>items();</script>
</body>
</html>
script.js:
var title, content;
function items(){
angular.module('myApp', []).controller('ctrl', function($scope) {
$scope.items = [
{fieldOne:"field1", fieldTwo:"field1 content"},
{fieldOne:"field2", fieldTwo:"field2 content"}
];
$scope.parentFunc=function(titleTmp,contentTmp){
title=titleTmp;
content=contentTmp;
var OpenWindow = window.open('popUp.html','_blank','width=500, height=400');
return false;
}
});
}
function codeAddress() {
document.getElementById("title").innerHTML=title;
document.getElementById("content").innerHTML=content;
}
popUp.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript" src="script.js"></script>
</head>
<body onload="codeAddress();">
<h1 id="title"></h1>
<div id="content"></div>
</body>
</html>
The new pop up window open as expected, but the h1 and div in it get undefined. I tried to debug it, and I saw that after the first two lines of parentFunc are executed, the global variables title and content get what I expect and they are not undefined. However, when the third line is executed and the new window get opened- the global variables are undefined.
Why the two global variables are undefined in the pop up window?
And how can I solve this?
Your method won't work : you are trying to reload the script.jsand then, the vars are reinitialized.
Add your vars in the URL :
var OpenWindow = window.open('popUp.html?title='+titleTmp+'&content='+contentTmp,'_blank','width=500, height=400');
Then, in your second page, read those parameters :
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="text/javascript">
function codeAddress(){
var title = GET_TITLE_FROM_PARAMETER;
var content = GET_CONTENT_FROM_PARAMETER;
document.getElementById("title").innerHTML=title;
document.getElementById("content").innerHTML=content;
}
</script>
</head>
<body onload="codeAddress();">
<h1 id="title"></h1>
<div id="content"></div>
</body>
</html>
And of course, remove codeAddress from the first page as it's useless.
FYI, to get the parameters values, please check this answer.

display an image only when button is clicked

Just beginning to learn HTML & Javascript.
I have the following code, which works. however, because I have have an img tag in my body it is trying to show a place holder for an image before I click the button. How can I stop this.
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tesco JSONP</title>
<script type="text/javascript">
function picture(){
var pic = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"
document.getElementById('bigpic').src = pic.replace('90x90', '225x225');
}
</script>
</head>
<body>
<img id="bigpic" src="bigpic" />
<button onclick="picture()">Enlarge</button>
</body>
</html>
Best wishes.
Add style "display:none" to picture tag
<img id="bigpic" src="bigpic" style="display:none;"/>
And in function picture change it for show image
document.getElementById('bigpic').style.display='block';
There is demo: http://jsfiddle.net/eX5kx/
Use display property in css, try this:
javascript:
function showPicture() {
var sourceOfPicture = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg";
var img = document.getElementById('bigpic')
img.src = sourceOfPicture.replace('90x90', '225x225');
img.style.display = "block";
}
html:
<img style="display:none;" id="bigpic" src="bigpic" />
<button onclick="showPicture()">Enlarge</button>
I like shin solution, i would do the same thing myself. However theres a lot of way to do that, another option is to put a tiny trasparent image as default and then replace like you did to the other one. like this:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Tesco JSONP</title>
<script type="text/javascript">
function picture(){
var pic = "http://img.tesco.com/Groceries/pi/118/5000175411118/IDShot_90x90.jpg"
document.getElementById('bigpic').src = pic.replace('90x90', '225x225');
}
</script>
</head>
<body>
// tiny trasparent image
<img id="bigpic" src="https://maps.gstatic.com/mapfiles/markers2/dd-via-transparent.png" alt="" />
<button onclick="picture()">Enlarge</button>
</body>
</html>
this way no css is needed but like i said before i prefer Shin's solution.

Part of the webpage on a new window

If I have some hidden element on a page, that contains some content, how can I create a link and when user clicks it, browser would open a new window and show the content (only the content, for example some json data)?
ps. I know that's probably bad idea to have some hidden content on the page. It's better to put an action link that will get the content from the server.. But it involves many other headaches and it wasn't me who created the page, so please just let me know if there's a comparatively easy solution...
Please use http://okonet.ru/projects/modalbox/index.html with inline content setting
You could pass the (URL encoded) contents of the hidden element as an argument in the URL when opening the second page. That argument could then be (unencoded and) inserted into the body of the second page when it loads.
The following example works locally on OS X. On other operating systems, the example may need to be placed on an actual web server before it will work:
page1.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page 1</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
function openwindow(){
window.open("page2.html?html="+escape($("#myDiv").html()));
}
</script>
<style>
.hidden {
visibility: hidden;
}
</style>
</head>
<body>
Click Me!
<div class="hidden" id="myDiv">
<img src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/6e/HTML5-logo.svg/200px-HTML5-logo.svg.png">
<p>See the HTML5 specification</p>
</div>
</body>
</html>
page2.html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Page 2</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
jQuery.extend({
// from: http://paulgueller.com/2011/04/26/parse-the-querystring-with-jquery/
parseQuerystring: function(){
var nvpair = {};
var qs = window.location.search.replace('?', '');
var pairs = qs.split('&');
$.each(pairs, function(i, v){
var pair = v.split('=');
nvpair[pair[0]] = pair[1];
});
return nvpair;
}
});
</script>
<script>
$(document).ready(function(){
$(document.body).html(unescape(jQuery.parseQuerystring().html));
});
</script>
<style>
.hidden {
visibility: hidden;
}
</style>
</head>
<body>
<!-- this will be replaced -->
</body>
</html>

Categories