css background image displays when user clicks link problem - javascript

I updated my post. Now it says "link is not defined" "thisLink[link].scopeObject = new Image();" It's important that the link remains though because it is a property of linkObj that holds the current link. I use the [] as a property rather than dot notation due to the looping ability it provides.
<script type="text/javascript">
window.onload = init;
var linkObj = new Object();
var listItems = new Object();
function init() {
for(var i=0; i < document.links.length; i++) {
var link = document.links[i];
linkObj[link] = link;
setupClick(linkObj);
}
}
function setupClick(thisLink) {
thisLink[link].scopeObject = new Image();
thisLink[link].scopeObject.src = thisLink[link].id + "Img.png";
thisLink[link].onclick = rollClick;
}
function rollClick() {
var list = document.getElementById("target").childNodes;
for(var i=0; i < list.length; i++) {
if(list[i].nodeName == "LI") {
var id = list[i] + i;
listItems[id] = id;
}
}
for(id in listItems){
if(listItems[id].indexOf(this[link].id) > -1) {
listItem[id].style.backgroundImage = this[link].scopeObject.src;
}
}
}
</script>
<ul id="target">
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
<div id="mainContent">
<div id="navLinks">
<ul>
<li>Home</li>
<li>About</li>
<li>Products</li>
<li>Contact</li>
</ul>

I believe the trouble is in this line: var linkObj[link] = document.links[i];. You need to remove the var command at the front of that line. I presume your linkObj has been declared somewhere else in your code and you're attempting to insert a new value into it. If not, please post more complete code and I can look further into it.
-- EDITED BELOW --
Then my statement "I presume you defined linkObj elsewhere." is incorrect. You may need to go with this instead: var linkObj = document.links[i];. The var command creates variables. Once they're created, assignment does not require the var command. Are you attempting to keep an object that has reference to all of the links for later, or do you only need to use each link once? If the former, outside of your init() function add this line: var linkObj = {};.
-- MORE EDITS --
Holy Cow. I'm not 100% sure what your end aim here is, but I think you should use something like this at first:
<script type="text/javascript">
window.onload = init;
function init() {
for (var i = 0; i < document.links.length; ++i) {
setupClick(document.links[i]);
}
}
function setupClick(thisLink) {
thisLink.scopeObject = new Image();
thisLink.scopeObject.src = thisLink[link].id + "Img.png";
thisLink.onclick = rollClick;
}
</script>
That's going to get you to a point where you're at least assigning properties to the links as they exist in the document.links array. The desired behavior from your rollClick function is a little hazy to me, but at least using that to start out with you're assigning properties to the links in your page.

Related

multiple onclick functions not possible?

I'm new to javascript (and I'm not allowed to use jQuery in class) and I'm struggling with onclick functions.
I want two separate sentences to turn green and the other one pink when I click on it so I gave both of them a different id.
for(var i = 0; i < content.length; i++){
var contentText = content[i];
var opening = document.createElement("p");
opening.id = "opening";
if(content[i].id ==="opening"){
opening.innerText = contentText.text;
}
textContainer1.append(opening);
document.getElementById("opening").onclick = function opening(){
document.getElementById("opening").style.color = 'green';
}
This is the first onclick function and it works like it should! But when I add the other sentence underneath:
for(var j = 0; j < content.length; j++){
var contentText2 = content[j];
var second = document.createElement("p");
second.className = "chapter-1";
second.id = "second";
if (content[j].id ==="second"){
second.innerText = contentText2.text;
}
textContainer2.append(second);
}
document.getElementById("second").onclick = function second(){
document.getElementById("second").style.color = 'pink';
}
The second one doesn't work anymore. I really can't figure out how to solve this and I need several ones in the same file. Can someone please help?
EDIT
I found out that it only works for the first thing in the json list, and not for the second, or third, etc. So I think I need a for loop to search within the elements, but I'm not sure how to do that in this case...
New answer
I think you've missed a } in the first bit of code.
for(var i = 0; i < content.length; i++){
var contentText = content[i];
var opening = document.createElement("p");
opening.id = "opening";
if(content[i].id ==="opening"){
opening.innerText = contentText.text;
}
textContainer1.append(opening);
}
document.getElementById("opening").onclick = function opening(){
document.getElementById("opening").style.color = 'green';
}
Old answer with probably better code
I may be misunderstanding you, but if you want your sentences to go green/pink when clicking on them, you just need the second function in each of your examples.
<p id="opening" onclick="opening();">opening</p>
<p id="second" onclick="second();">second</p>
<script>
var opening = function() {
document.getElementById("opening").style.color = "green";
}
var second = function() {
document.getElementById("second").style.color = "pink";
}
</script>
This makes opening go green when one clicks it and second go pink when one clicks it.
Alternatively, if you want to assign it without adding onclick in HTML:
document.getElementById("opening").onclick = function() {
document.getElementById("opening").style.color = "green";
}
document.getElementById("second").onclick = function() {
document.getElementById("second").style.color = "pink";
}

Load var n from localStorage and loop n times

I'm trying to learn JS and this is my little app.
Every time I press the "INSTANTIATE" button, it instantiates a tomatoe.png in my <div>.
When the user reloads the page, the tomatoe.png should appear as many times as they've pressed the "INSTANTIATE" button.
This is the code. For this purpose, I created a variable (i), and it increments on every button press.
I planned to save this variable into localStorage, and when the page gets reloaded, I want to call a loop function that instantiates the tomatoe.png i times.
function popUp() {
var img = document.createElement("img");
img.src = "tomato.png";
var src = document.getElementById("header");
src.appendChild(img);
i++;
localStorage.setItem("apples", i);
}
<button onclick="popUp()">INSTANTIATE</button>
<div id="header"></div>
So, when the user reloads the page, as many tomatoes should appear as many times they've pressed the button.
I think I have to use a loop, but I don't know how.
Just get the item in localStorage and loop until it reaches 0, creating a new image each time (localStorage don't works in StackOverflow snippets here because of security reasons, but you get the point).
var i = 0;
function popUp() {
newImage();
i++;
localStorage.setItem("apples", i);
}
function newImage() {
var img = document.createElement("img");
img.src = "tomato.png";
var src = document.getElementById("header");
src.appendChild(img);
}
var oldi = Number(localStorage.getItem("apples"));
while (oldi > 0) {
oldi--;
newImage();
}
<button onclick="popUp()">INSTANTIATE</button>
<div id="header"></div>
First of all, you have to declare i outside your function (in case you haven't done it already) and give it a value of zero, if it isn't exist in the Local Storage:
let i = localStorage.getItem("apples") || 0;
Then, create a loop, that loops i times:
for(let n = 0; n < i; n++){}
And finally, just create tomatoes:
const img = document.createElement("img");
img.src = "tomato.png";
const src = document.getElementById("header");
src.appendChild(img);
So, the full code should look like this:
document.addEventListener('DOMContentLoaded', function(){
function popUp() {
createTomato()
i++;
localStorage.setItem("apples", i);
}
function createTomato() {
const img = document.createElement("img");
img.src = "tomato.png";
const src = document.getElementById("header");
src.appendChild(img);
}
document.getElementById("instantiate").addEventListener("click", popUp)
let i = localStorage.getItem("apples") || 0;
for (let n = 0; n < i; n++) createTomato();
})
<button id="instantiate">INSTANTIATE</button>
<div id="header"></div>
Try it on codepen.io

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.

Elements By ClassName Failing

I am creating sliding menus in JavaScript, and the following is my init() function:
function init() {
var menus = new Array();
var allElems = document.getElementsByTagName("*");
for (var i = 0; i < allElems.length; i++) {
alert(allElems[i]);
if (allElems[i].className == "navG") {
alert(allElems[i]);
menus.push(allElems[i]);
}
}
/* assign the openMenu function to the onclick event for each
Menus item */
for (var i = 0; i < menus.length; i++) {
alert(menus[i]);
menus[i].onclick=openMenu;
}
document.getElementById("logo").onclick = closeMenu;
document.getElementById("linkList").onclick = closeMenu;
document.getElementById("main").onclick = closeMenu;
}
The problem seems to be in the first for loop. This is definitely the correct class name..just for reference, this is the type of HTML that I am referring to:
<div class="navG" id="gallery1" style="position: absolute; top: 180px; left: -150px; " >
Is there an obvious, or not so obvious reason, that this is not adding the elements to menus?
You got a bug here
document.getElementById("logo").onclick = closeMenu();
document.getElementById("linkList").onclick = closeMenu();
document.getElementById("main").onclick = closeMenu();
You calling closeMenu, not assigning it.
Needs to be
document.getElementById("logo").onclick = closeMenu;
document.getElementById("linkList").onclick = closeMenu;
document.getElementById("main").onclick = closeMenu;
In the page you linked to, in your family.js script, this line:
window.onLoad = init();
says to run the init function immediately and assign its return value to window.onLoad. Because it is running immediately the actual document hasn't been parsed yet so it doesn't find any of your elements. You need to say this:
window.onload = init;
which assigns a reference to the init function to window.onload so that that function will be run later after all of the elements have been parsed.
Also onload should have a lowercase l.
(There are some other problems in your code, e.g., you don't seem to have elements with the ids "linkList" or "main", but I think what I said above is the main problem with the part you are asking about.)
Whoops, you're missing quotes around that "navG" in the first loop.

Find an anchor in a Div with javascript

In javascript I have a reference to a div. In that div is an anchor element with a name='foundItem'
How do I get a reference to the anchor with the name foundItem which is in the Div I have the reference of?
There are 'many' foundItem anchors in other divs on the page. I need 'this' DIVs one.
// assuming you're not using jquery or mootools
// assume div is mydiv
var lst = mydiv.getElementsByTagName('a');
var myanchor;
for(var i=0; i<lst.length; ++i) {
if(lst[i].name && lst[i].name == 'foundItem') {
myanchor = lst[i];
break;
}
}
// the mootools method
var myanchor = $(mydiv).getElement('a[name=foundItem]');
You can use the getElementsByTagName method to get the anchor elements in the div, then look for the one with the correct name attribute:
var found = null;
var e = divReference.getElementsByTagName('A');
for (var i=0; i < e.length; i++) {
if (e[i].name && e[i].name == 'foundItem') {
found = e[i];
break;
}
}
If found is not null, you got the element.
If you happen to use the jQuery library, you can let it do the searching:
var found = null;
var e = $(divReference).find('a[name=foundItem]');
if (e.length == 1) found = e.get(0);
Use a JavaScript library like jQuery and save yourself time.
var theAnchor = $('#divId a[name=foundItem]');
Using jquery, it's dead easy:
<script type="text/javascript">
$(function(){
var item = $("#yourDivId a[name=foundItem]")
)};
</script>
Update:
As per the comments, if you have control over what to id/name/class your anchor tag/s, it would be best to apply a class to them:
<div id="firstDiv">
test
</div>
<div id="secondDiv">
test another one
</div>
<!-- and so forth -->
<script type="text/javascript">
$(function(){
var item = $("#firstDiv a.foundItem");
alert(item.html()); // Will result in "test"
var item2 = $("#secondDiv a.foundItem");
alert(item2.html()); // Will show "test another one"
)};
</script>
If you're doing anything with javascript, jQuery saves you tons of time and is worth investing the effort to learn well. Start with http://api.jquery.com/browser/ to get an intro to what's possible.
Not sure if this helps, but wanted a function to handle the load of a page dynamically and scroll to the anchor of choice.
function scrollToAnchor(anchor_val) {
alert("" + anchor_val);
var page = document.getElementById('tables');
var found = null;
var cnt = 0;
var e = document.getElementsByTagName('a');
for (var i = 0; i < e.length; i++) {
if (e[i].name && e[i].name == anchor_val) {
found = e[i];
break;
}
cnt++;
}
if (found) {
var nPos = found.offsetTop;
alert("" + nPos);
page.scrollBy(0, nPos);
} else {
alert('Failed with call of scrollToAnchor()' + cnt);
}
}

Categories

Resources