change target of javascript to div - javascript

I have some img tags with id's but through validating my code I realized that the tags were missing a src. The only problem is, is that in my javascript these img id's are targeted and when I changed them to a div instead the images disappeared.
Basically this page is staff profiles with images and content, the user clicks an arrow and it goes to the next profile. How the code works is that the images are in an external javascript file and when I click something on page and inspect the html I saw that the image appears within the image tags in HTML.This javascript was given to me so I am not sure what to change, I don't know much about javascript. Let me know if any clarification or code is needed, this is very difficult to explain as I don't understand what is going on.
HTML -the problem
<img id='staff_image' class='staff_image'></img>
<img id='staff_name' class='staff_name'></img>
HTML -the page
<div id='staff_slider' class='slider'>
<div class='staff_container'>
<img id='staff_image' class='staff_image' src"#" alt="image"
</div>
<img id='staff_name' class='staff_name' src"#" alt="image"></div>
<div id='staff_details' class='staff_details'></div>
</div>
<div class='slider_navigation'>
<img class='navLeft' src='../assets/images/staff_profile/slider/navLeft.png' alt= "nav left" onclick='navigate(-1);'/>
<img class='navRight' src='../assets/images/staff_profile/slider/navRight.png' alt="nav right" onclick='navigate(1);'/>
</div>
</div>
<script src="staff_profiles.js"></script>
<script src="slider.js"></script>
<script>
navigate(0);
</script>
JAVASCRIPT- slider.js (this is for two arrow buttons that scroll through the profiles)
var slider_index = 0;
function navigate(direction){
slider_index += direction;
if(slider_index < 0)
{
slider_index = profiles.length - 1;
}
else if(slider_index == profiles.length)
{
slider_index = 0;
}
loadProfile(profiles[slider_index]);
}
function loadProfile(profile)
{
var staff_image = document.getElementById('staff_image');
staff_image.src = imgPath + profile.img;
var staff_name = document.getElementById('staff_name');
staff_name.src = titlePath + profile.title;
var staff_details = document.getElementById('staff_details');
staff_details.innerHTML = profile.details;
}
JAVASCRIPT - staff_profiles.js (seperate file, these are the links to the images needed for the profiles, the content are in strings)
var imgPath = "../assets/images/staff_profile/staff/";
var titlePath = "../assets/images/staff_profile/titles/";
var profiles =
[
//
{
img:"fin.jpg",
title:"fin.png",
details:"<p>Stunt pilot with the Red Arrows (UK airforce stunt team), has served in combat choppers in 3 recent wars, and fears nothing except small dogs and single women.</p>" +
"<p>Owns an Extra EA-200 for the ultimate full stunt flight experience, and flies all our other fixed wing craft much more sedately when required. And, yes, that is his real name. He's Irish and he doesn't want to talk about it.</p>"
},
//
{
img:"hans.jpg",
title:"hans.png",
details:"<p>Hans has flown almost everything there is to fly. Hanshas has flown almost everything there is to fly. He first took the controls of a small plane at 12 years old, and flew solo when he was 14. After a few years flying anything anywhere he settled into a series of test pilot jobs but left that because he prefers company when hes in the air.</p>"
},
//
{
img:"john.jpg",
title:"john.png",
details:"<p>With over 10,000 hours piloting helicopters in the bush and mountains of the Southern Alps for deer recovery and mountain rescue operations, Doc is well qualified to land you and your friends in remote parts of the country that only he knows about. He ll help you plot your route, drop extra provisions where you want them, and pick you up when your done.</p>"
},
{
img:"wendy.jpg",
title:"wendy.png",
details:"<p>13 years commercial pilot in Africa, Russia and South America, during which she survived 3 crashes (none her own fault, she maintains). Owns a Cessna-172Skyhawk P that is ideal for low level sight seeing, rides a Harley and is a ski instructor during the seas</p>"
}
];

You need to change the following lines in the loadProfile function
var staff_image = document.getElementById('staff_image');
var myimg = staff_image.getElementsByTagName('img')[0];
myimg.src = imgPath + profile.img;
The HTML could be like this
<div id='staff_image'>
<img src"#" alt="image"/>
</div>
Hope it's useful to you

Related

HTML buttons and event listeners

I wanted to make a dynamic table view where a button was clicked to reveal a Table Row however, I get an error when I try to change the text of the button.
window.onload = () => {
const buttons = document.getElementsByTagName("button")
console.log(buttons)
const info = document.getElementsByTagName("tr")
// let a = 1
for (let elem in info) {
if (info.id != "info") continue
else info.splice(info.indexOf(elem), 1)
}
for (i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function onClick(a = 1) {
if (a % 2 == 0) {
info[i].style.visibility = "hidden"
buttons[i].innerText = "View More" // wrong
} else {
info[i].style.visibility = "visible"
buttons[i].innerText = "View Less" // wrong
}
a++
})
}
}
<button>Show Contents</button>
<table>
<tr id="info" style="visibility:hidden;">
<td width="80%">
<p style="width:80%;text-align:center; margin-left:1%">
The Planetarium is located on the first floor of the Science Centre. The planetarium has a shape of a sphere, 16.30 meters in diameter, the dome could also be used for extreme-wide-projections and other enhanced multi-media shows. It has a seating capacity
of 140 the digital theatre of Planetarium facilitates the observation of planets, moon, stars, nebula, displayed on full dome through an advance technology and thus Astronomy Secrets will be shared with the students and general public. High resolution
projectors operated through Digester 3 technology with digital audio system will provide a dazzling shows and that would be unforgettable experience. The shows will be in 3 languages Gujarati, Hindi and English.
</p>
</td>
</table>
Error:
Uncaught TypeError: Cannot set properties of undefined (setting 'innerText')
at HTMLButtonElement.onClick
Suggestions:
Use "display" style, instead of "visibility", to don't let the space occupied on the page when it's not visible;
It's not good idea have multiple elements with the same id (like "info"), because that breaks the rules of HTML;
To show and hide, use read directly info from css, instead of use a auxiliary variable;
The document.getElementsByTagName returns an object, not an array. The way to navigate is using the classic way.
Next, your code with some fixes:
window.onload = () => {
const buttons = document.getElementsByTagName("button")
//console.log(buttons)
const info = document.getElementsByTagName("tr")
// let a = 1
let newInfo = [];
for (let i = 0; i < info.length; i++) {
if (info[i].id === "info"){
newInfo.push(info[i]);
}
}
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener("click", function onClick() {
if (newInfo[i].style.visibility !== "hidden") {
newInfo[i].style.visibility = "hidden"
// Suggestion: use "display" style, instead of "visibility", to don't let the space ocupied on the page, when it's not visible
//newInfo[i].style.display = "none"
buttons[i].innerText = "View More" // wrong
}
else {
newInfo[i].style.visibility = "visible"
buttons[i].innerText = "View Less" // wrong
//newInfo[i].style.display = ""
}
})
}
}
<button>Show Contents</button>
<table>
<tr id="info" style="visibility:hidden;">
<td width="80%">
<p style="width:80%;text-align:center; margin-left:1%">
1 - The Planetarium is located on the first floor of the Science Centre. The planetarium has a shape of a sphere, 16.30 meters in diameter, the dome could also be used for extreme-wide-projections and other enhanced multi-media shows. It has a seating capacity of 140 the digital theatre of Planetarium facilitates the observation of planets, moon, stars, nebula, displayed on full dome through an advance technology and thus Astronomy Secrets will be shared with the students and general public. High resolution projectors operated through Digester 3 technology with digital audio system will provide a dazzling shows and that would be unforgettable experience. The shows will be in 3 languages Gujarati, Hindi and English.
</p>
</td>
</table>
<button>Show Contents</button>
<table>
<tr id="info" style="visibility:hidden;">
<td width="80%">
<p style="width:80%;text-align:center; margin-left:1%">
2 - The Planetarium is located on the first floor of the Science Centre. The planetarium has a shape of a sphere, 16.30 meters in diameter, the dome could also be used for extreme-wide-projections and other enhanced multi-media shows. It has a seating capacity of 140 the digital theatre of Planetarium facilitates the observation of planets, moon, stars, nebula, displayed on full dome through an advance technology and thus Astronomy Secrets will be shared with the students and general public. High resolution projectors operated through Digester 3 technology with digital audio system will provide a dazzling shows and that would be unforgettable experience. The shows will be in 3 languages Gujarati, Hindi and English.
</p>
</td>
</table>

When hovering over text, change the text and background image

I am new to coding and wrapping my head around utilization of JavaScript it still hard for me.
My problem is that I have like a navigation menu, those have one word in them. I want that when I hover over navigation menu background of the entire site changes corresponding to the navigation menu item I hovered over, and the navigation item changes it's content from one word to more words.
I tried searching on Google, YouTube and here on stackoverflow of course. I managed to get working code but it feels like a mess and bad practice and I wasn't able to implement good answers to my code or they were using ES5 JavaScript which differentiates from ES6 a lot.
Here are the things I tried:
1 . First thing i tried is to create a function with if statements. Didn't quite work. Probably because of my low understanding of JS.
I tried then to addEventListener to every navigation menu item individually. And that works, but it's a mess. Just blocks of copy / pasted code.
I tried then to create a function again and have onmouseover = "function()" inside of HTML but didn't work either.
Then I tried to do it over CSS but my inexperience started to show again it seems. I wasn't able to succeed in it with :before and :after either.
I have some example code here.
<div id='bckgimg'>
<div class="nav-container">
<a href='/nav1' id='nav-nav1' class='nav'>NAV1</a>
<a href='/nav2' id='nav-nav2' class='nav'>NAV2</a>
<a href='/nav3' id='nav-nav3' class='nav'>NAV3</a>
<a href='/nav4' id='nav-nav4' class='nav'>NAV4</a>
</div>
</div>
<style>
#bckgimg{
background-image: url('https://picsum.photos/id/1/300/200');
}
</style>
<script>
const nav1 = document.getElementById('nav-nav1');
const nav2 = document.getElementById('nav-nav2');
const nav3 = document.getElementById('nav-nav3');
const nav4 = document.getElementById('nav-nav4');
const bckgImg = document.getElementById("bckgimg");
// repeat this code 3 more times with nav2, nav3, nav4
// code bellow checks if <div> is hovered over and changes background image <div> + changes text of the <div>
navStories.addEventListener('mouseenter', e => {
bckgImg.style.backgroundImage = "url('https://picsum.photos/id/2/300/200')";
navStories.innerHTML = "MY NAV 1 LONGER";
});
// if <div> is hovered out it returns the original picture to background <div> and original text of <div>
navStories.addEventListener('mouseleave', e => {
bckgImg.style.backgroundImage = "url('https://picsum.photos/id/1/300/200')";
navStories.innerHTML = "NAV1";
});
</script>
Alright figured it out! Took me whole day but I got it!
First of, on JSfiddle where it says JavaScript + No-Library (pure JS) you need to press on the arrow on the side and for LOAD TYPE choose no wrap - bottom of body.
Second, if you have code which has an error which is represented by red color by JSfiddle your whole directory (JavaScript directory in my case) won't run. Error in my code was that I just commented all the code I didn't need at the bottom with /* but didn't close it since I thought it wasn't important.
Third, the solution itself:
// changed whole thing, which was my point. Reduced code from ~50 lines to two functions in 16 lines
// onHover function has a property of i which corresponds to numbers in html on onmouseover and out
// created arrays with IDs, what text and image should be after hovering
// i will correspond to numbers in html which in turn correspond to numbers in arrays
function onHover(i) {
const array = ["nav-nav1", "nav-nav2", "nav-nav3", "nav-nav4"];
const strings = ["MY NAV 1 LONGER", "MY NAV 2 LONGER", "MY NAV 3 LONGER", "MY NAV 4 LONGER"];
const bckgUrls = ["url('https://picsum.photos/id/2/300/200", "url('https://picsum.photos/id/3/300/200')", "url('https://picsum.photos/id/4/300/200')", "url('https://picsum.photos/id/5/300/200')"];
var idvar = document.getElementById(array[i]);
idvar.innerHTML = `${strings[i]}`;
document.getElementById("bckgimg").style.backgroundImage = `${bckgUrls[i]}`;
}
// when hovering out from text do same like onHover just the reverse
// return values of navigation menu and background image to original
function outHover(i) {
const array = ["nav-nav1", "nav-nav2", "nav-nav3", "nav-nav4"];
const strings = ["NAV1", "NAV2", "NAV3", "NAV4"];
var idvar = document.getElementById(array[i]);
idvar.innerHTML = `${strings[i]}`;
document.getElementById("bckgimg").style.backgroundImage = "url('https://picsum.photos/id/1/300/200')";
}
#bckgimg{
background-image: url('https://picsum.photos/id/1/300/200');
overflow: hidden;
background-position: center center;
background-size: cover;
height: 300px;
}
a {
color: white;
text-decoration: none;
}
<div id='bckgimg'>
<!-- because we changed ON LOAD options now onmouseover and on mouseout will pull functions from JS -->
<div class="nav-container">
<a onmouseover="onHover(0)" onmouseout="outHover(0)" href='/nav1' id='nav-nav1' class='nav'>NAV1</a><br>
<a onmouseover="onHover(1)" onmouseout="outHover(1)" href='/nav2' id='nav-nav2' class='nav'>NAV2</a><br>
<a onmouseover="onHover(2)" onmouseout="outHover(2)" href='/nav3' id='nav-nav3' class='nav'>NAV3</a><br>
<a onmouseover="onHover(3)" onmouseout="outHover(3)" href='/nav4' id='nav-nav4' class='nav'>NAV4</a><br>
</div>
</div>

How to fix function to where it allows the next function to correctly compute?

hope everyone is doing well. I am new to JavaScript and trying to do a little exercise but having trouble. When I load the page, and click the Blue button, the orange text and red text disappear like I want to, but if I click the Red button after. All of it disappears. I am trying to create something where if I click on one of the colors, the colors that isn't clicked on disappear and only the colored text remains. I want to be able to do it endlessly.
I've tried various websites but haven't been able to get the help I want.
JavaScript
function blueChange() {
var firstHidden = document.getElementById('orange');
firstHidden.style.display = "none";
var secondHidden = document.getElementById('red');
secondHidden.style.display = "none";
}
function redChange() {
var thirdHidden = document.getElementById('blue');
thirdHidden.style.display = "none";
var fourthHidden = document.getElementById('orange');
fourthHidden.style.display = "none";
}
document.getElementById('blueButton').addEventListener("click",
blueChange);
document.getElementById('redButton').addEventListener("click",
redChange);
HTML
<section>
<button id="blueButton">
Blue
</button>
<button id="orangeButton">
Orange
</button>
<button id="redButton">
Red
</button>
</section>
<section id="allParagraphs">
<p style="color:orange" id="orange" class="colors">
So far, authorities are still in the process of collecting
information, and details on exact numbers or the cause of the die off
have been scarce. Several turtle species live in the area—hawksbills,
leatherbacks, olive ridleys, and green turtles.
</p>
<p style="color:red" id="red" class="colors">
In both of these previous cases, red tide was found to be the
cause of the turtles' deaths. "Red tide" is a term that commonly refers
to when colonies of algal blooms grow out of control. Sometimes,
depending on the specific organisms and conditions, they can become toxic
for marine life. Flair ups can occur in fresh and salt water, and they
can be exacerbated by runoff from chemicals like pesticides or untreated
sewer water. For turtles, ingesting the toxic blooms can be deadly.
</p>
<p style="color:blue" id="blue" class="colors">
Mike Liles has lived in El Salvador for the past decade working
on turtle conservation as the director of the country's branch of the
Eastern Pacific Hawksbill Initiative. From his sources on the ground,
Liles has learned that as many as 300 additional dead turtles may have
been found in an area called Isla Tasajara 30 miles west of Jiquilisco
Bay. El Salvador's environmental ministry has yet to confirm this.
</p>
The problem is that you never reset the color that matches the button. So for example, when you click the Blue button, that correctly hides the Orange and Red text. Then if you click the Red button, again, it correctly hides the Orange and Blue text. But the Red text is still hidden from the first time you clicked the Blue button -- you never un-hide that text!
Try adding code to each event listener to reset the color that matches the button clicked. For example:
function blueChange() {
var firstHidden = document.getElementById('orange');
firstHidden.style.display = "none";
var secondHidden = document.getElementById('red');
secondHidden.style.display = "none";
// reset blue.
var blueElement = document.getElementById('blue');
blueElement.style.display = "block";
}
As explained in srk's answer above, you need to reset the display property each time.
In addition, i would suggest that you create a general function like bellow:
function toggleColorDisplay(color){
let colors = ['red', 'orange', 'blue']; // you can add any color you want
colors.forEach(col => {
let elem = document.getElementById(color);
if(col == color) elem.style.display = 'block' // or whatever the original display property is
else elem.style.display = 'none';
})}
Then you call that function:
document.getElementById('blueButton').addEventListener("click", function() {
toggleColorDisplay('blue');
};
Repeat this call for each button, just change the argument to the appropriate color

Trying to randomly display an image, out of 4 images, based on its src

I have a card game in which I'm trying to randomly display an image out of four four possible images. THE CODEPEN: http://codepen.io/anon/pen/udBan The images are displayed in the html as follows:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="js/main.js"></script>
<link rel="stylesheet" type="text/css" href="css/css.css">
</head>
<body>
<h1>Card Match!</h1>
<div id="main_image">
<!-- <div> -->
<div><img src="images/back-of-card.png"></div>
<div><img src="images/back-of-card.png"></div>
<div><img src="images/back-of-card.png"></div>
<div><img src="images/back-of-card.png"></div>
<div id="button_div">
<button id="start">Start Game</button>
<button id="reset">Reset Game</button>
<button id="cheat">Cheat</button>
</div>
</div>
</body>
</html>
I have the functionality going such that when you click on a card, it will randomly change it to either a king or a queen. Crazy intense game, I know.
Note the cheat button.
The function that I wrote is:
var king_array = ["images/King.png","images/King.png"];
var queen_array = ["images/Queen.png","images/Queen.png"];
$(function() {
$("#cheat").click(function() {
if (king_array.length == 1){
src = king_array.shift();
back_of_card_array = $('img:not([src="images/King.png"])');
random = Math.floor(Math.random() * back_of_card_array.length);
back_of_card_array[random].attr('src',src);
console.log("turned king");
} else if (queen_array.length == 1){
src = queen_array.shift();
back_of_card_array = $('img:not([src="images/Queen.png"])');
random = Math.floor(Math.random() * back_of_card_array.length);
back_of_card_array[random].attr('src',src);
console.log("turned queen")
} else {
console.log("turn a card to cheat!")
}
});
});
What I was expecting this to do was return an array of the unflipped cards back_of_card_array = $('img:not([src="images/King.png"])');,which it does, and then when I click the cheat button, to use back_of_card_array[random].attr('src',src); to select a randomized image and set it to src, which was either king or queen, depending on what was already flipped (I guess if both a king and a queen are flipped it will turn a king...another issue that I don't intend to get into here).
Thus, how can I get an unflipped card to flip, based on what is already flipped?
Thanks! http://codepen.io/anon/pen/udBan
I'm not sure I follow your question, but I'll take a swing.
So I'm not clear on the rules of your game, but it sounds like you want to flip either a king or a queen, such that if a King is already face-up you show a queen, and vice versa. Is that right?
If so, I'd maintain an object of flipped cards (if order is important, keep that by making it an array and just pushing in each one as you go). Then you can either brute force your way through the array (i.e. re-randomizing if the card doesn't match your criteria) or else have two decks (one that's all kings, one that's all queens) and use deck selection to force the right "kind" of card.

javascript image swap affects too many images

ive got a collection of 3 images, two small one large. id like to to be set up so when you click on a small image, it takes the place of the larger one. The issue is that I have a collection of three of these three images so when you click on a small image, it takes the spot of all three large images. Any suggestions for getting it so it only takes the spot of the large image in its section? Heres some code. Thanks!
$(document).ready(function(){
$('img').click(function(){
var url = $(this).attr('src');
$(this).parents('.picture-container').find('.large-picture > img').attr('src', url);
$('.large-picture > img').attr('src', url);
$(this).attr('src', bigUrl);
});
});
picture section (there are three of these)
<div class = 'picture-container'>
<div class = 'large-picture' style = 'width:50%;height:100%;float:left;'>
<img src = 'close_table_dupontstudios.png' width = '100%' height = '100%'>
</div>
<div class = 'picture-content' style = 'float:right;width:45%;height:100%;'>
<div class='picture-title'>BOUTIQUE PRODUCTION STUDIO</div>
<div class='picture-text'>We built a boutique full service production studio that allows for one, two and three person filmed interviews and conversations. We have studio lights, a three camera set-up and remote monitoring. Additionally, our Infinity Wall creates a clean and professional look that allows the film to be about the message.</div>
<div class = 'small-picture-wrapper'>
<div class = 'small-picture' style = 'float:left;height:100%;'>
<img src = 'hair_and_makeup_dupontstudios.png' width = '100%' height = '100%'>
</div>
<div class = 'small-picture' style = 'float:right;height:100%;'>
<img src = 'infinity_wall_dupontstudios.png' width = '100%' height = '100%'>
</div>
</div>
</div>
</div>
There are a bunch of jquery slideshow/carousel plugins that should do what you need.
If you need a snippet to just do this one thing, you might need to clarify what you want.
From what I gather, there should only be 3 images at any time. One is large, the other two are small ( like thumbnails? ). You want to click on a small image and have it replace the large image ( so the small image becomes as large as the large image and takes it's position?).
DOes the large image then shrink and take the place of the image just selected.
Just explain it like you would to a little kid.
I don't think I changed anything in the html other than the img src's, so this should work:
<script>
$(document).ready( function(){
$(".small-picture > img").click( function(){
var small_img = $(this);
var small_img_src = small_img.attr("src");
var img_container = small_img.closest(".picture-container");
var large_img = img_container.find(".large-picture > img");
var large_img_src = large_img.attr("src");
large_img.attr("src", small_img_src);
small_img.attr("src", large_img_src);
});
});
</script>

Categories

Resources