show/hide <section> element using javascript - javascript

I'm testing some simple HTML/JavaScript code, however, when I open the site, the show/hide scripts only hides the first section, but doesn't do anything to the other sections. I would like it so that for every image clicked, the section corresponding to that image is displayed.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<title>Profile Bird</title>
<link rel="stylesheet" type="text/css" href="../CSS/styles.css">
<script>
function displayBird1() {
document.getElementById("intro").style.display = "none";
documemt.getElementById("king").style.display = "block";
document.getElementById("owl").style.display = "none";
document.getElementById("eagle").style.display = "none";
document.getElementById("starling").style.display = "none";
}
function displayBird2() {
document.getElementById("intro").style.display = "none";
documemt.getElementById("king").style.display = "none";
document.getElementById("owl").style.display = "block";
document.getElementById("eagle").style.display = "none";
document.getElementById("starling").style.display = "none";
}
function displayBird3() {
document.getElementById("intro").style.display = "none";
documemt.getElementById("king").style.display = "none";
document.getElementById("owl").style.display = "none";
document.getElementById("eagle").style.display = "block";
document.getElementById("starling").style.display = "none";
}
function displayBird4() {
document.getElementById("intro").style.display = "none";
documemt.getElementById("king").style.display = "none";
document.getElementById("owl").style.display = "none";
document.getElementById("eagle").style.display = "none";
document.getElementById("starling").style.display = "block";
}
</script>
</head>
<body>
<header>
<h1>Cool Twitching</h1>
<img class="imageBanner" src="../images/banner.jpg">
<p>Birdwatching is not a hobby it is a lifestyle</p>
</header>
<nav>
<ul>
<li>Home</li>
<li>News</li>
<li>In Profile</li>
<li>Excursions</li>
<li>Applications</li>
</ul>
</nav>
<main>
<div>
<img class="smallImage" src="../images/bird1.jpg" onclick="displayBird1()" onmouseover="test()">
<img class="smallImage" src="../images/bird2.jpg" onclick="displayBird2()">
<img class="smallImage" src="../images/bird3.jpg" onclick="displayBird3()">
<img class="smallImage" src="../images/bird4.jpg" onclick="displayBird4()">
</div>
<section id="intro" style="display:block" >
<p style="font-size: 16px"> Please click an image to choose what bird information to display </p>
</section>
<section id="king" style="display:none;">
<p>To see previous profile birds click the images on the left.</p><br><br>
<h2>Kingfisher</h2>
<img class="smallImageRight" src="../images/bird1.jpg">
<p>Kingfishers or Alcedinidae are a family of small to medium-sized, brightly colored birds in the order Coraciiformes. They have a cosmopolitan distribution, with most species found outside the Americas. The family contains 114 species and is divided into three subfamilies and 19 genera. All kingfishers have large heads, long, sharp, pointed bills, short legs, and stubby tails. Most species have bright plumage with only small differences between the sexes.
<br><br> Most species are tropical in distribution, and a slight majority are found only in forests. They consume a wide range of prey usually caught by swooping down from a perch. While kingfishers are usually thought to live near rivers and eat fish, many species live away from water and eat small invertebrates. Like other members of their order, they nest in cavities, usually tunnels dug into the natural or artificial banks in the ground. Some kingfishers nest in arboreal termite nests. A few species, principally insular forms, are threatened with extinction. In Britain, the word "kingfisher" normally refers to the common kingfisher.</p>
</section>
<section style="display:none;" id="owl">
<p>To see previous profile birds click the images on the left.</p><br><br>
<h2>Barn Owl</h2>
<img class="smallImageRight" src="../images/bird2.jpg">
<p>The barn owl (Tyto alba) is the most widely distributed species of owl and one of the most widespread of all birds. It is also referred to as the common barn owl, to distinguish it from other species in its family, Tytonidae, which forms one of the two main lineages of living owls, the other being the typical owls (Strigidae). The barn owl is found almost everywhere in the world except polar and desert regions, Asia north of the Himalayas, most of Indonesia, and some Pacific islands.
<br><br>
Phylogenetic evidence shows that there are at least three major lineages of barn owl, one in Europe, western Asia and Africa, one in southeast Asia and Australasia, and one in the Americas, and some highly divergent taxa on islands. Accordingly, some authorities split the group into the western barn owl for the group in Europe, western Asia and Africa, the American barn owl for the group in the Americas, and the eastern barn owl for the group in southeast Asia and Australasia. There is a considerable variation between the sizes and colour of the approximately 28 subspecies but most are between 33 and 39 cm in length with wingspans ranging from 80 to 95 cm. The plumage on head and back is a mottled shade of grey or brown, the underparts vary from white to brown and are sometimes speckled with dark markings. The face is characteristically heart-shaped and is white in most subspecies. This owl does not hoot, but utters an eerie, drawn-out shriek.
</p>
</section>
<section style="display:none;" id="eagle">
<p>To see previous profile birds click the images on the left.</p><br><br>
<h2>Golden Eagle</h2>
<img class="smallImageRight" src="../images/bird3.jpg">
<p>The golden eagle (Aquila chrysaetos) is one of the best-known birds of prey in the Northern Hemisphere. It is the most widely distributed species of eagle. Like all eagles, it belongs to the family Accipitridae. These birds are dark brown, with lighter golden-brown plumage on their napes. Immature eagles of this species typically have white on the tail and often have white markings on the wings. Golden eagles use their agility and speed combined with powerful feet and massive, sharp talons to snatch up a variety of prey, mainly hares, rabbits, marmots and other ground squirrel.
<br><br>
Golden eagles maintain home ranges or territories that may be as large as 77 sq miles. They build large nests in cliffs and other high places to which they may return for several breeding years. Most breeding activities take place in the spring; they are monogamous and may remain together for several years or possibly for life. Females lay up to four eggs, and then incubate them for six weeks. Typically, one or two young survive to fledge in about three months. These juvenile golden eagles usually attain full independence in the fall, after which they wander widely until establishing a territory for themselves in four to five years.
<br><br>
</p>
</section>
<section style="display:none;" id="starling">
<p>To see previous profile birds click the images on the left.</p><br><br>
<h2>Starling</h2>
<img class="smallImageRight" src="../images/bird3.jpg">
<p>Starlings are small to medium-sized passerine birds in the family Sturnidae. The name "Sturnidae" comes from the Latin word for starling, sturnus. Many Asian species, particularly the larger ones, are called mynas, and many African species are known as glossy starlings because of their iridescent plumage. Starlings are native to Europe, Asia and Africa, as well as northern Australia and the islands of the tropical Pacific. Several European and Asian species have been introduced to these areas as well as North America, Hawaii and New Zealand, where they generally compete for habitats with native birds and are considered to be invasive species. The starling species familiar to most people in Europe and North America is the common starling, and throughout much of Asia and the Pacific, the common myna is indeed common.
<br><br>
Starlings have strong feet, their flight is strong and direct, and they are very gregarious. Their preferred habitat is fairly open country, and they eat insects and fruit. Several species live around human habitation and are effectively omnivores. Many species search for prey such as grubs by "open-bill probing", that is, forcefully opening the bill after inserting it into a crevice, thus expanding the hole and exposing the prey; this behaviour is referred to by the German verb zirkeln.
</p>
</section>
</main>
<footer>
<p>All images copyrighted by Cool Twitchers</p>
</footer>
</body>
</html>
Any help is appreciated.

<!DOCTYPE html>
<html>
<head>
<title>Profile Bird</title>
<link rel="stylesheet" type="text/css" href="../CSS/styles.css">
<script>
function displayBird1() {
document.getElementById("intro").style.display = "none";
document.getElementById("king").style.display = "block";
document.getElementById("owl").style.display = "none";
document.getElementById("eagle").style.display = "none";
document.getElementById("starling").style.display = "none";
}
function displayBird2() {
document.getElementById("intro").style.display = "none";
document.getElementById("king").style.display = "none";
document.getElementById("owl").style.display = "block";
document.getElementById("eagle").style.display = "none";
document.getElementById("starling").style.display = "none";
}
function displayBird3() {
document.getElementById("intro").style.display = "none";
document.getElementById("king").style.display = "none";
document.getElementById("owl").style.display = "none";
document.getElementById("eagle").style.display = "block";
document.getElementById("starling").style.display = "none";
}
function displayBird4() {
document.getElementById("intro").style.display = "none";
document.getElementById("king").style.display = "none";
document.getElementById("owl").style.display = "none";
document.getElementById("eagle").style.display = "none";
document.getElementById("starling").style.display = "block";
}
function test() {
}
</script>
</head>
<body>
<header>
<h1>Cool Twitching</h1>
<img class="imageBanner" src="../images/banner.jpg">
<p>Birdwatching is not a hobby it is a lifestyle</p>
</header>
<nav>
<ul>
<li>Home</li>
<li>News</li>
<li>In Profile</li>
<li>Excursions</li>
<li>Applications</li>
</ul>
</nav>
<main>
<div>
<img class="smallImage" src="../images/bird1.jpg" onclick="displayBird1()" onmouseover="test()">
<img class="smallImage" src="../images/bird2.jpg" onclick="displayBird2()">
<img class="smallImage" src="../images/bird3.jpg" onclick="displayBird3()">
<img class="smallImage" src="../images/bird4.jpg" onclick="displayBird4()">
</div>
<section id="intro" style="display:block" >
<p style="font-size: 16px"> Please click an image to choose what bird information to display </p>
</section>
<section id="king" style="display:none;">
<p>To see previous profile birds click the images on the left.</p><br><br>
<h2>Kingfisher</h2>
<img class="smallImageRight" src="../images/bird1.jpg">
<p>Kingfishers or Alcedinidae are a family of small to medium-sized, brightly colored birds in the order Coraciiformes. They have a cosmopolitan distribution, with most species found outside the Americas. The family contains 114 species and is divided into three subfamilies and 19 genera. All kingfishers have large heads, long, sharp, pointed bills, short legs, and stubby tails. Most species have bright plumage with only small differences between the sexes.
<br><br> Most species are tropical in distribution, and a slight majority are found only in forests. They consume a wide range of prey usually caught by swooping down from a perch. While kingfishers are usually thought to live near rivers and eat fish, many species live away from water and eat small invertebrates. Like other members of their order, they nest in cavities, usually tunnels dug into the natural or artificial banks in the ground. Some kingfishers nest in arboreal termite nests. A few species, principally insular forms, are threatened with extinction. In Britain, the word "kingfisher" normally refers to the common kingfisher.</p>
</section>
<section style="display:none;" id="owl">
<p>To see previous profile birds click the images on the left.</p><br><br>
<h2>Barn Owl</h2>
<img class="smallImageRight" src="../images/bird2.jpg">
<p>The barn owl (Tyto alba) is the most widely distributed species of owl and one of the most widespread of all birds. It is also referred to as the common barn owl, to distinguish it from other species in its family, Tytonidae, which forms one of the two main lineages of living owls, the other being the typical owls (Strigidae). The barn owl is found almost everywhere in the world except polar and desert regions, Asia north of the Himalayas, most of Indonesia, and some Pacific islands.
<br><br>
Phylogenetic evidence shows that there are at least three major lineages of barn owl, one in Europe, western Asia and Africa, one in southeast Asia and Australasia, and one in the Americas, and some highly divergent taxa on islands. Accordingly, some authorities split the group into the western barn owl for the group in Europe, western Asia and Africa, the American barn owl for the group in the Americas, and the eastern barn owl for the group in southeast Asia and Australasia. There is a considerable variation between the sizes and colour of the approximately 28 subspecies but most are between 33 and 39 cm in length with wingspans ranging from 80 to 95 cm. The plumage on head and back is a mottled shade of grey or brown, the underparts vary from white to brown and are sometimes speckled with dark markings. The face is characteristically heart-shaped and is white in most subspecies. This owl does not hoot, but utters an eerie, drawn-out shriek.
</p>
</section>
<section style="display:none;" id="eagle">
<p>To see previous profile birds click the images on the left.</p><br><br>
<h2>Golden Eagle</h2>
<img class="smallImageRight" src="../images/bird3.jpg">
<p>The golden eagle (Aquila chrysaetos) is one of the best-known birds of prey in the Northern Hemisphere. It is the most widely distributed species of eagle. Like all eagles, it belongs to the family Accipitridae. These birds are dark brown, with lighter golden-brown plumage on their napes. Immature eagles of this species typically have white on the tail and often have white markings on the wings. Golden eagles use their agility and speed combined with powerful feet and massive, sharp talons to snatch up a variety of prey, mainly hares, rabbits, marmots and other ground squirrel.
<br><br>
Golden eagles maintain home ranges or territories that may be as large as 77 sq miles. They build large nests in cliffs and other high places to which they may return for several breeding years. Most breeding activities take place in the spring; they are monogamous and may remain together for several years or possibly for life. Females lay up to four eggs, and then incubate them for six weeks. Typically, one or two young survive to fledge in about three months. These juvenile golden eagles usually attain full independence in the fall, after which they wander widely until establishing a territory for themselves in four to five years.
<br><br>
</p>
</section>
<section style="display:none;" id="starling">
<p>To see previous profile birds click the images on the left.</p><br><br>
<h2>Starling</h2>
<img class="smallImageRight" src="../images/bird3.jpg">
<p>Starlings are small to medium-sized passerine birds in the family Sturnidae. The name "Sturnidae" comes from the Latin word for starling, sturnus. Many Asian species, particularly the larger ones, are called mynas, and many African species are known as glossy starlings because of their iridescent plumage. Starlings are native to Europe, Asia and Africa, as well as northern Australia and the islands of the tropical Pacific. Several European and Asian species have been introduced to these areas as well as North America, Hawaii and New Zealand, where they generally compete for habitats with native birds and are considered to be invasive species. The starling species familiar to most people in Europe and North America is the common starling, and throughout much of Asia and the Pacific, the common myna is indeed common.
<br><br>
Starlings have strong feet, their flight is strong and direct, and they are very gregarious. Their preferred habitat is fairly open country, and they eat insects and fruit. Several species live around human habitation and are effectively omnivores. Many species search for prey such as grubs by "open-bill probing", that is, forcefully opening the bill after inserting it into a crevice, thus expanding the hole and exposing the prey; this behaviour is referred to by the German verb zirkeln.
</p>
</section>
</main>
<footer>
<p>All images copyrighted by Cool Twitchers</p>
</footer>
</body>
</html>
fix typo documemt to document
declare test or remove it from mouse over event

Your problem resides on the declaration of document on every function.
Your code is:
//check the "m" instead of "n" on the word "document"
documemt.getElementById("king").style.display = "block";
when it should be:
document.getElementById("king").style.display = "block";

Related

I am trying to use vanilla JS to highlight clicked anchor and remove the previously highlighted anchor

This is my first post and I don't know what I am doing yet, so please bear with me.
I am trying to use vanilla JS to highlight a clicked anchor and remove the previously highlighted anchor.
I am not sure why it is not working but I am new at this.
My CodePen
below is just the JS. .nav-link is the link class. active is the class that should manipulate it after the click.
window.onload = afterClick;
function afterClick(){
//set an on off array to toggle.
let linkClass = document.querySelectorAll(".nav-link");
linkClass.forEach(link => link.addEventListener("click", function(){
if (link.classList.contains("active")) {
link.classList.remove("active");
link.classList.add("active");
}}));
}
Thank you!
Instead of onload you can listen to hashchange event instead to achieve this like:
window.addEventListener("hashchange", () => {
let hash = window.location.hash;
if (hash) {
let linkClass = document.querySelectorAll(".nav-link");
linkClass.forEach(x => x.classList.remove("active"))
document.querySelector('a[href="' + hash + '"]').classList.add("active");
}
});
So, whenever the url hash will change, it will remove the active class from all the links using:
linkClass.forEach(x => x.classList.remove("active"))
and then it will search for the link having that hash and add the active class to that link only using:
document.querySelector('a[href="' + hash + '"]').classList.add("active");
Working Demo:
window.addEventListener("hashchange", () => {
let hash = window.location.hash;
if (hash) {
let linkClass = document.querySelectorAll(".nav-link");
linkClass.forEach(x => x.classList.remove("active"))
document.querySelector('a[href="' + hash + '"]').classList.add("active");
}
});
#main-doc{font-family:Montserrat,sans-serif}#navbar{float:left;position:fixed;font-family:Montserrat,sans-serif;font-weight:700;min-width:230px;max-width:231px;height:100vh;background:url(https://image.freepik.com/free-vector/elegant-white-texture-background_23-2148431731.jpg);margin-top:-10px;margin-left:-10px;margin-right:40px;margin-bottom:25px;border:1px solid #000}#navbar header{padding:14px;font-size:1.8em;text-align:center;border:1px solid #000}#navbar a{display:block;color:#000;text-decoration:none;padding:15px;font-size:1.1em;text-align:center;border:1px solid #000;border-top:0}.main-section header{margin-left:30px;font-family:Notable,sans-serif;font-size:1.4rem}.main-section ul li{list-style-type:none;font-size:1.3em;padding-bottom:6px}.main-section{margin-left:230px;margin-right:50px;padding-top:20px}#main-doc{padding-bottom:60px}code{font-size:1rem;font-family:Montserrat,sans-serif}.active{color:orange!important;background-color:#00f!important}#media only screen and (max-width:425px){#navbar{max-width:425px;min-width:200px;position:relative;width:100vw;height:auto}.nav-link{margin-top:0;width:100vw}.main-section{margin-left:5px;margin-right:10px;padding-top:20px}.main-section ul{padding-left:5px}.navbar a{padding:0}}
<style>
#import url('https://fonts.googleapis.com/css2?family=Montserrat&family=Notable&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Montserrat:wght#700&display=swap');
</style>
<!-- font-family: 'Montserrat', sans-serif;
font-family: 'Notable', sans-serif; -->
<nav id="navbar">
<header style="color: #FFDF01 ;background: url(https://img.freepik.com/free-photo/blue-with-vignette-marble-texture-background-with-copy-space_23-2148327728.jpg?size=626&ext=jpg)">Common Sharks</header>
<a class="nav-link" href="#About_Sharks" id="aboutSharks">About Sharks</a>
<a class="nav-link" href="#The_Great_White">The Great White</a>
<a class="nav-link" href="#Oceanic_White_Tip">Oceanic White Tip</a>
<a class="nav-link" href="#Bull_Shark">Bull Shark</a>
<a class="nav-link" href="#Tiger_Shark">Tiger Shark</a>
</nav>
<main id="main-doc">
<section class='main-section' id="About_Sharks">
<header>About Sharks</header>
</br>
<ul><span style="font-size: 2.1em; margin-left: 5px;">B</span>efore we can talk about the most deadly sharks in the world, there are a few interesting facts that will help you understand sharks as a species better.</br>
</br>
<li>Sharks do not have bones</li>
<p>Sharks use their gills to filter oxygen from the water. They are a special type of fish known <i>Elasmobranch</i>, which translates into: </br>fish made of cartilaginous tissues—the clear gristly stuff that your ears and nose tip are made of. This
category also includes rays, sawfish, and skates. Their cartilaginous skeletons are much lighter than true bone and their large livers are full of low-density oils, both helping them to be buoyant. </p>
<p>Even though sharks don't have bones, they still can fossilize. As most sharks age, they deposit calcium salts in their skeletal cartilage to strengthen it. The dried jaws of a shark appear and feel heavy and solid; much like bone. These same minerals
allow most shark skeletal systems to fossilize quite nicely. The teeth have enamel so they show up in the fossil record too.</p>
</br>
<li>Most sharks have good eyesight</li>
<p>Most sharks can see well in dark lighted areas, have fantastic night vision, and can see colors. The back of sharks’ eyeballs have a reflective layer of tissue called a tapetum. This helps sharks see extremely well with little light.</p>
<br><br>
<li>Sharks have special electroreceptor organs</li>
<p>Sharks have small black spots near the nose, eyes, and mouth. These spots are the <i>ampullae of Lorenzini</i> – special electroreceptor organs that allow the shark to sense electromagnetic fields and temperature shifts in the ocean.</p>
<br>
<li>Shark skin feels similar to sandpaper</li>
<p>Shark skin feels exactly like sandpaper because it is made up of tiny teeth-like structures called placoid scales, also known as dermal denticles. These scales point towards the tail and help reduce friction from surrounding water when the shark
swims.
</p>
<br>
<li>Sharks can go into a trance</li>
<p>When you flip a shark upside down they go into a trance like state called tonic immobility. This is the reason why you often see sawfish flipped over when our scientists are working on them in the water.</p>
</br>
<li>Sharks have been around a very long time</li>
<p>Based on fossil scales found in Australia and the United States, scientists hypothesize sharks first appeared in the ocean around 455 million years ago.</p>
<br>
<li>Scientists age sharks by counting the rings on their vertebrae</li>
<p><code>Vertebrae contain concentric pairs of opaque and translucent bands. Band pairs are counted like rings on a tree and then scientists assign an age to the shark based on the count. Thus, if the vertebrae has 10 band pairs, it is assumed to be 10 years old. Recent studies, however, have shown that this assumption is not always correct. Researchers must therefore study each species and size class to determine how often the band pairs are deposited because the deposition rate may change over time. Determining the actual rate that the bands are deposited is called <i>validation</i>.</code></p>
<br>
<li>Blue sharks are really blue</li>
<p><code>The blue shark displays a brilliant blue color on the upper portion of its body and is normally snowy white beneath. The mako and porbeagle sharks also exhibit a blue coloration, but it is not nearly as brilliant as that of a blue shark. In life, most sharks are brown, olive, or grayish.</code></p>
<br>
<li>Each whale shark’s spot pattern is unique as a fingerprint</li>
<p>Whale sharks are the biggest fish in the ocean. They can grow to 12.2 meters and weigh as much as 40 tons by some estimates! Basking sharks are the world's second largest fish, growing as long as 32 feet and weighing more than five tons.</p>
<br>
<li>Some species of sharks have a spiracle that allows them to pull water into their respiratory system while at rest</li>
<p>Most sharks have to keep swimming to pump water over their gills A shark's spiracle is located just behind the eyes which supplies oxygen directly to the shark's eyes and brain. Bottom dwelling sharks, like angel sharks and nurse sharks, use this
extra respiratory organ to breathe while at rest on the seafloor. It is also used for respiration when the shark's mouth is used for eating.</p>
<br>
<li>Not all sharks have the same teeth</li>
<p>
Mako sharks have very pointed teeth, while white sharks have triangular, serrated teeth. Each leave a unique, tell-tale mark on their prey. A sandbar shark will have around 35,000 teeth over the course of its lifetime! </p>
<br>
<li>Different shark species reproduce in different ways</li>
<p>
Sharks exhibit a great diversity in their reproductive modes. There are oviparous (egg-laying) species and <i>viviparous</i> (live-bearing) species. Oviparous species lay eggs that develop and hatch outside the mother's body with no parental care
after the eggs are laid.</p>
</section>
<section class='main-section' id="The_Great_White">
<header>The Great White</header>
<ul>
The legendary great white shark is far more fearsome in our imaginations than in reality. As scientific research on these elusive predators increases, their image as mindless killing machines is beginning to fade.
</br>
</br>
<li>Shark Attacks</li>
Of the <i><b>100-plus</b></i> annual shark attacks worldwide, fully one-third to one-half are attributable to great whites. However, most of these are not fatal, and new research finds that great whites, who are naturally curious, are "sample biting"
then releasing their victims rather than preying on humans. It's not a terribly comforting distinction, but it does indicate that humans are not actually on the great white's menu.
</br>
</br>
<li>Characteristics</li>
Great whites are the largest predatory fish on Earth. They grow to an average of 15 feet in length, though specimens exceeding 20 feet and weighing up to 5,000 pounds have been recorded. They have slate-gray upper bodies to blend in with the rocky coastal
sea floor, but get their name from their universally white underbellies. They are streamlined, torpedo-shaped swimmers with powerful tails that can propel them through the water at speeds of up to 15 miles per hour. They can even leave the water
completely, breaching like whales when attacking prey from underneath.
</br>
</br>
<li>Hunting Adaptations</li>
Highly adapted predators, their mouths are lined with up to 300 serrated, triangular teeth arranged in several rows, and they have an exceptional sense of smell to detect prey. They even have organs that can sense the tiny electromagnetic fields generated
by animals. Their main prey items include sea lions, seals, small toothed whales, and even sea turtles, and carrion.
</br>
</br>
<li>Population</li>
</code>Found in cool, coastal waters throughout the world, there is no reliable data on the great white's population. However, scientists agree that their number are decreasing precipitously due to overfishing and accidental catching in gill nets, among
other factors, and they are considered a vulnerable species.</code>
</ul>
</section>
<section class='main-section' id="Oceanic_White_Tip">
<header>Oceanic White Tip</header>
<ul>
</br>
<li>Characteristics</li>
This is an active, almost fearless shark also associated with human attacks. MarineBio considers this shark the most potentially dangerous after great whites, tiger, and bull sharks, especially for open-ocean divers. This species is likely responsible
for open-ocean attacks following air or sea disasters.
</br>
</br>
<li>Behavior</li>
Oceanic whitetips can be very aggressive and unpredictable in the presence of potential prey. Sold commercially fresh, frozen, smoked, and dried-salted for human consumption; hides for leather, fins for shark fin soup, liver oil for vitamins, and processed
into fishmeal.
</br>
This species is a widespread and common large pelagic shark of warm oceanic waters. It presumably has a low reproductive capacity, but is extremely abundant and wide-ranging and is subject to fishery pressure as a common bycatch species with tuna and
other pelagic species. This bycatch is reportedly either inadequately reported or unrecorded. The fins are highly prized in trade although the carcass is often discarded. Fishery pressure is likely to persist, if not increase in future, and the
impact of this fishing pressure is presently unknown.
</br>
</br>
<li>Population</li>
<code>The oceanic whitetip shark, <i>Carcharhinus longimanus</i>, is listed as Critically Endangered.</code>
</ul>
</section>
<section class='main-section' id="Bull_Shark">
<header>Bull Shark</header>
<ul>
Bull sharks are aggressive, common, and usually live near high-population areas like tropical shorelines. They are not bothered by brackish and freshwater, and even venture far inland via rivers and tributaries.
</br>
</br>
<li>Human Encounters</li>
Because of these characteristics, many experts consider bull sharks to be the most dangerous sharks in the world. Historically, they are joined by their more famous cousins, great whites and tiger sharks, as the three species most likely to attack humans.
</br>
</br>
<li>Characteristics</li>
Bull sharks get their name from their short, blunt snout, as well as their pugnacious disposition and a tendency to head-butt their prey before attacking. They are medium-size sharks, with thick, stout bodies and long pectoral fins. They are gray on top
and white below, and the fins have dark tips, particularly on young bull sharks.
</br>
</br>
<li>Hunting</li>
They are found cruising the shallow, warm waters of all the world’s oceans. Fast, agile predators, they will eat almost anything they see, including fish, dolphins, and even other sharks. Humans are not, per se, on their menus. However, they frequent
the turbid waters of estuaries and bays, and often attack people inadvertently or out of curiosity.
</br>
</br>
<li>Threats to Survival</li>
<code>Bull sharks are fished widely for their meat, hides, and oils, and their numbers are likely shrinking. One study has found that their average lengths have declined significantly over the past few decades.</code>
</ul>
</section>
<section class='main-section' id="Tiger_Shark">
<header>Tiger Shark</header>
<ul>
Tiger sharks are named for the dark, vertical stripes found mainly on juveniles. As these sharks mature, the lines begin to fade and almost disappear.
</br>
</br>
<li>Shark Attacks</li>
These large, blunt-nosed predators have a duly earned reputation as man-eaters. They are second only to great whites in attacking people. But because they have a near completely undiscerning palate, they are not likely to swim away after biting a human,
as great whites frequently do.
</br>
</br>
<li>Hunting</li>
They are consummate scavengers, with excellent senses of sight and smell and a nearly limitless menu of diet items. They have sharp, highly serrated teeth and powerful jaws that allow them to crack the shells of sea turtles and clams. The stomach contents
of captured tiger sharks have included stingrays, sea snakes, seals, birds, squids, and even license plates and old tires.
</br>
</br>
<li>Population</li>
Tiger sharks are common in tropical and sub-tropical waters throughout the world. Large specimens can grow to as much as 20 to 25 feet in length and weigh more than 1,900 pounds.
</br>
</br>
<li>Threats to Survival</li>
<code>They are heavily harvested for their fins, skin, and flesh, and their livers contain high levels of vitamin A, which is processed into vitamin oil. They have extremely low repopulation rates, and therefore may be highly susceptible to fishing pressure. They are listed as near threatened throughout their range.</code>
</ul>
</section>
</main>
First problem I found is that in your if loop :
if (link.classList.contains("active")) {
link.classList.remove("active");
link.classList.add("active");
}
.. only triggers on an element that already has the "active" class you want it to add, so it's not doing anything right now. If we take your existing if loop to iterate through the other and remove the active class from them, then we can safely add the active class to the link that was clicked:
window.onload = afterClick;
function afterClick() {
let linkClass = document.querySelectorAll(".nav-link");
// Add eventListener
linkClass.forEach((originalLink) =>
originalLink.addEventListener("click", function () {
let linkElems = document.querySelectorAll(".nav-link");
// Clear "active class from the same links"
linkElems.forEach((linkElem)=>{
if (linkElem.classList.contains("active")) {
linkElem.classList.remove("active");
}
});
//add the |"active" class to the originally clicked elem
originalLink.classList.add("active");
})
);
}
Hope it helps! :)

JS/CSS div expand not working

I have the code below which I believe should make the 'content_cards' appear when you click on the 'title' div, and then hide when you click on it again but it doesn't seem to be working. It just seems to refresh the page.
I tried doing it by using the button as the selector but as I have other buttons on the page it won't work.
$(document).ready(function() {
$(".title").on("click", function() {
$("#content1").toggleClass("expando1");
$("#content2").toggleClass("expando2");
});
});
.expando1 {
max-height: 60rem;
}
.expando2 {
max-height: 200rem;
}
.content_cards {
overflow: hidden;
transition: all 2s ease;
max-height: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="title">
<button>expand / collapse</button>
</div>
<div class="container">
<div class="card">
<h4>Trevor Macdonald</h4>
<div class="content_cards" id="content1">
<p>Born in Trinidad in 1939, Trevor worked in various aspects of the media including local newspapers, radio and television. He joined the Caribbean regional service of the BBC World Service in 1960 as a producer, before moving to London at the end of that decade to work for BBC Radio, London.
Moving to Independent Television News (ITN) in 1973, he rose steadily through the ranks. He's served as news, sports and diplomatic correspondent before moving on to become diplomatic editor and newscaster. Twice voted Newscaster of the year, McDonald is perceived as the face of ITN after years of fronting its flagship 'News at Ten' bulletin.
An accomplished journalist, he has penned several books including autobiographies on cricketers Clive Lloyd and Viv Richards. His own biography, 'Fortunate Circumstances', was published in 1993. Once viewed as the best-spoken person in the country and was reported to have fronted a two-year inquiry into the state of language learning. It warned that government education policy failed to teach pupils the necessary language skills needed for later life.
In 1992 he received an OBE in the Queen's Honours List, and received a knighthood in 1999. He continues to be the anchor for the News at Ten, and presents Tonight with Trevor McDonald, which was launched in 1999.</p>
</div>
</div>
<div class="card">
<h4>Shirley Bassey</h4>
<div class="content_cards" id="content2">
<p>Shirley Bassey was born in Tiger Bay, Cardiff in 1937, the youngest of seven children. In 1952, Shirley left school to work in the packing department of a sausage factory, all the while singing at local clubs which catered to working men.
It wasn’t long before Shirley turned professional, In 1955, Shirley appeared at the Astor Club in London, and the world began to take notice of her incredible talent.
Her first single was “Burn My Candle”, but her first real hit was “Banana Boat Song”. Her debut album, “Born to Sing the Blues” was released in 1958. Hit after hit soon followed, with “As I Love You” and “Kiss Me, Honey Honey, Kiss Me” appearing on record charts simultaneously. Shirley’s first big international hit was 1964’s “Goldfinger” from the James Bond film of the same name.
In 1977 she received the Brit Award for Best British Female Solo Artist in the previous 25 years. Bassey has been called "one of the most popular female vocalists in Britain during the last half of the 20th century." In 2000, Bassey was made a Dame by Queen Elizabeth II for services to the performing arts.</p>
</div>
</div>
<div class="card">
<h4>Sadiq Khan</h4>
<div class="content_cards" id="content2">
<p>Sadiq was born in St George’s Hospital in Tooting, growing up on a council estate in Earlsfield. He attended local state schools Fircroft Primary School (where he is now a governor), Ernest Bevin Comprehensive School and Burntwood Girls Secondary School. His father was a London Transport bus driver for more than 25 years.
Prior to becoming the MP for Tooting, Sadiq was a Human Rights solicitor and was a founding partner of one of the country's leading Human Rights firms. In his final year of practising law he was listed as one of the county's leading lawyers in two separate categories of law in the Chambers and Partners directory 2004-05 (Human Rights and Police law).
Previously the Shadow Secretary of State for Transport, Sadiq was the first ever BAME politician to be elected to the Labour Party’s Shadow Cabinet, and was the youngest member of Ed Miliband’s cabinet. He served in a number of ministerial posts during the last Labour Government. He is a member of the Labour Party’s National Executive Committee (NEC), the Labour Party’s governing and policy-making body.
Khan was elected Mayor of London in the 2016 mayoral election, succeeding Conservative Party Mayor Boris Johnson. He resigned as MP for Tooting on 9 May 2016. His election as Mayor of London made him the city's first ethnic minority mayor, and the first Muslim to become mayor of a major Western capital. Khan held the largest personal mandate of any politician in the history of the United Kingdom, and the third largest personal mandate in Europe.</p>
</div>
</div>
<div class="card">
<h4>Arthur Wharton</h4>
<div class="content_cards" id="content2">
<p>Wharton was born in Jamestown, Gold Coast (now Accra, Ghana). In 1884, aged 19, Arthur moved to England to train as a Methodist preacher at Cleveland College, Darlington.
It was whilst at College that he began his amazing sporting careers, competing at this stage as a 'gentleman amateur'. He excelled at everything he tried (even setting a record time for cycling between Preston and Blackburn in 1887).
In 1886 Arthur became the fastest man in Britain winning the Amateur Athletics Association national 100 yards champion at Stamford Bridge, London - the first time the trophy was won by a Northerner.
His sporting prowess was spotted at Darlington Football Club, where he was selected to play as goalkeeper. Arthur became the first black professional footballer in Britain. In 2014 a 16ft statue of Arthur was unveiled at the FA's national football centre in Burton.</p>
</div>
</div>
<div class="card">
<h4>Dame Kelly Holmes</h4>
<div class="content_cards" id="content2">
<p>Born in Pembury, Kent, the daughter of Derrick Holmes, a Jamaican-born car mechanic, and an English mother, Pam Norman. Her mother, 18 at the time of her birth, married painter and decorator Michael Norris, whom Holmes regards as her father, seven years later, and the couple had two more children (Kevin, born 1977 and Stuart, born 1980) before splitting up in 1987. Holmes grew up in Hildenborough and attended Hildenborough CEP School, and then Hugh Christie Comprehensive School in Tonbridge at the age of 12.
She started training for athletics at the age of 12, joining Tonbridge Athletics Club, where she was coached by David Arnold and went on to win the English schools 1500 metres in her second season in 1983.[citation needed] Her hero was British middle distance runner Steve Ovett, and she was inspired by his success at the 1980 Summer Olympics
She specialised in the 800 metres and 1500 metres events won a gold medal for both distances at the 2004 Summer Olympics in Athens, making her the first British woman to win two gold medals and the country’s first double gold medallist at the same games since Albert Hill in 1920. She set British records in numerous events and still holds the records over the 600, 800, 1000, and 1500 metres distances. </p>
</div>
</div>
<div class="card">
<h4>Zayn Malik</h4>
<div class="content_cards" id="content2">
<p>Zayn Malik was born on January 12, 1993, in Bradford, England, to a family of English-Pakistani descent. He had an early love for singing and performing, and at the age of 17 he competed in the television competition The X Factor. He was teamed up with four other male contestants to form the group act One Direction, who went on to become one of the most popular boy bands in music history. The group's debut studio album Up All Night was released in November 2011. It topped the charts in 16 countries. The lead single, "What Makes You Beautiful", was an international commercial success, reaching number one in the UK and number four in the US; it has since been certified four and six times platinum in the US and Australia, respectively.
He is an official ambassador of the British Asian Trust charity group, contributing to improving the lives of disadvantaged people living in South Asia. With his former group One Direction, he contributed to African fundraising events with Comic Relief. In March 2016, he bought a box at Bradford City for underprivileged children to watch football, named after his maternal grandfather Walter Brannan. As of April 2015, shortly after he left One Direction, Malik's net worth was £25 million ($41 million).As of April 2016, his net worth is £30 million ($49 million).
Malik left the group in March 2015. The following year, he released his first solo album. Malik signed a solo recording contract with RCA Records in 2015, with his debut studio album Mind of Mine released on 25 March 2016. The album and its lead single, "Pillowtalk", reached number one in a number of countries, including the United Kingdom, United States, Australia, Canada and New Zealand, with Malik becoming the first British male artist to debut at number one in both the UK and US with his debut single and debut album. Worldwide, he had the highest first-day and weekly streams for a debut artist.</p>
</div>
</div>
<div class="card">
<h4>Ignatius Sancho</h4>
<div class="content_cards" id="content2">
<p>Sancho was born around 1729 on board a slave ship en route to the West Indies. He spent the first two years of his life enslaved in Grenada. Orphaned in infancy, he was brought to England by his master at the age of two or three and given to three maiden sisters living in Greenwich.
He was rescued by the Duke of Montagu, who lived nearby in Blackheath. The Duke, encountering the Sancho by accident, took a liking to his frankness of manner. Sancho eventually ended up working as a butler in the Montagu household.
He went on to compose music and write poetry and plays and in 1773, Sancho and his wife set up a grocer's shop in Westminster. Sancho was very well known and his shop became a meeting place for some of the most famous writers, artists, actors and politicians of the day.
Perhaps most notable Ignatius Sancho was known for being the first Black Briton to vote in a UK election. After his death in 1780, Sancho's letters were published in a book, which became an immediate best seller. Five editions of the book were published and his writing was used as evidence to support the movement to end slavery. It was this piece that led Sancho become the first African author to have his work published in this country.</p>
</div>
</div>
</div>
That is because the .expando classes have the same specificity as the .content_cards and the .content_cards is defined last in the CSS, so it is the last that is applied.
Just putting the .content_cards above the .expando ones will fix it.
.content_cards {
overflow: hidden;
transition: all 2s ease;
max-height: 0;
}
.expando1 {
max-height: 60rem;
}
.expando2 {
max-height: 200rem;
}
Otherwise make more specific rules, like
.content_cards.expando1 {
max-height: 60rem;
}
.content_cards.expando2 {
max-height: 200rem;
}
.content_cards {
overflow: hidden;
transition: all 2s ease;
max-height: 0;
}

Read more expand text

Trying to remake this effect where the user clicks 'read more' and the bio expands and they can click 'show less' to display partial bio. I thought maybe it was some javascript to display or hide different sections of html. I ripped part of the html and Javascript I thought created this effect and put it into code.pen.io but it didn't work.. What'd I do wrong?
http://www.nealcommunities.com/about/management-team/
My code pen try : http://codepen.io/danieltaki/pen/VjJbkQ
HTML
<li>
<div class="excerpt RTETextWrapper">
<div>
<p>Pat is a conscientious developer, a master builder and the visionary leader of Neal Communities. He is the third generation in his family to be a builder/developer in this community. A graduate of the esteemed Wharton School of Finance, he was a respected member of the Florida Legislature for 12 years, serving our community in the House of Representatives and the Senate, where he was appointed Chairman of the Senate Appropriations Committee. During this time, he was honored with every one of Florida’s top environmental awards. Since 1970, Pat Neal has built more than 10,000 homes with integrity and commitment in the finest communities, and the awards he has earned in his builder developer career continue to complement his political accomplishments. He is a respected leader and inspirational philanthropist. A snapshot of Pat Neal’s accomplishments:</p>
<ul>
<li>Florida State Senate 1978-86</li>
<li>Chairman, Senate Appropriations Committee</li>
<li>Chairman, Committee on Natural Resources</li>
<li>Member, Florida House of Representatives, 1974-78</li>
<li>Chair, Florida Commission on Ethics, 2000-01</li>
<li>Chair, Florida Commission on Ethics, 2002</li>
</ul> Read More...
</div>
</div>
<!-- content -->
<div class="content RTETextWrapper">
<div>
<p>Pat is a conscientious developer, master builder and visionary leader of Neal Communities. He is the third generation in his family to be a builder/developer in this community. A graduate of the esteemed Wharton School of Finance, he was a respected member of the Florida Legislature for 12 years, serving our community in the House of Representatives and the Senate, where he was appointed Chairman of the Senate Appropriations Committee. During this time, he was honored with every one of Florida’s top environmental awards. Since 1970, Pat Neal has built more than 10,000 homes with integrity and commitment in the finest communities, and the awards he has earned in his builder developer career continue to complement his political accomplishments. He is a respected leader and inspirational philanthropist. A snapshot of Pat Neal’s accomplishments:</p>
<ul>
<li>Florida State Senate 1978-86</li>
<li>Chairman, Senate Appropriations Committee</li>
<li>Chairman, Committee on Natural Resources</li>
<li>Member, Florida House of Representatives, 1974-78</li>
<li>Chair, Florida Commission on Ethics, 2000-01</li>
<li>Chair, Florida Commission on Ethics, 2002</li>
<li>Sierra Club Legislative Award, 1984</li>
<li>Florida Audubon Society Legislative Award, 1983</li>
<li>Professional Achievement Award, Professional Builder Magazine</li>
<li>Best master Planned Community in the United States (University Park), National Association of Home Builders and Professional Builder Magazine</li>
<li>Hearthstone Builder Public Service Honor Roll, Builder Magazine and Hearthstone Advisors, 2002</li>
<li>Advisory Board, The Trust for Public Land, Florida 2001-2002</li>
<li>Board of Directors, Florida TaxWatch, Inc. 1989, 2000-present</li>
<li>TIGER Award from the Florida Education Association/United 1983</li>
<li>Four-time recipient of the Florida Association of Community Colleges Legislative Service Award</li>
<li>Allen Morris Award for Most Effective Member of the Senate in Committee 1984</li>
<li>Future of the Region Award – Best Community, Tampa Bay Regional Planning Council (University Park)</li>
<li>Ed H. Price Humanitarian Award 2002</li>
<li>John A. Clarke Humanitarian Award 2007</li>
<li>Best Boss, Sarasota Biz941 2007</li>
<li>Community Leadership Award 2008</li>
</ul> ...Read Less
</div>
</div>
<!-- content -->
<div class="clear"></div>
</li>
</div>
</div>
Javascript Code
$(function(){
// expand
$('ul .showMore').click(function(){
var $excerpt = $(this).parent().parent();
$excerpt.hide();
$excerpt.next('.content').show();
return false;
});
$('ul .showLess').click(function(){
var $content = $(this).parent().parent();
$content.hide();
$content.prev('.excerpt').show();
return false;
});
$('ul .showMore').text('read more');
$('ul .showLess').text('read less');
});
You did in fact forget to include jQuery in your CodePen, but additionally, the jQuery that was in place was still not working.
I've learned the hard way that navigating with lots of .parent() calls is not a good way to navigate the DOM.
Here's an Updated CodePen for your reference.
I've only changed two things:
I added the CSS to hide the content by default:
.content.RTETextWrapper {
display: none;
}
I modified your jQuery to use a more reliable method of finding the appropriate elements, using closest and find. And, for fun, I threw in some slideUp and slideDown animation:
// "No-conflict-safe" document ready
jQuery(function($) {
$('a.showMore').click(function() {
// Go UP the DOM and find the closest parent li, THEN find that li's .excerpt element
$(this).closest('li').find('.excerpt').slideUp('fast');
// Go UP the DOM and find the closest parent li, THEN find that li's .content element
$(this).closest('li').find('.content').slideDown('slow');
return false;
});
$('a.showLess').click(function() {
$(this).closest('li').find('.excerpt').slideDown('slow');
$(this).closest('li').find('.content').slideUp('fast');
return false;
});
});

On Click and Opacity for simple Biography slider

Can anyone help me, i have a simple yet complicated problem. I want to make it like below
Something like if you click on one picture the others will have a shade on it.
The page im working on now is http://www.3cwaremarketing.com/VisiSite/company-10/team/
Thanks for your help. You can see the details below.
HTML
function changeIt(objName) {
//The image object accessed through its id we mentioned in the DIV block which is going to be visible currently
var obj = document.getElementById(objName);
//An array that hold the IDs of images that we mentioned in their DIV blocks
var objId = new Array();
//Storing the image IDs into the array starts here
objId[0] = "image1";
objId[1] = "image2";
objId[2] = "image3";
objId[3] = "image4";
objId[4] = "image5";
//Storing the image IDs into the array ends here
//A counter variable going to use for iteration
var i;
//A variable that can hold all the other object references other than the object which is going to be visible
var tempObj;
//The following loop does the display of a single image based on its ID. The image whose ID we passed into this function will be the
//only image that is displayed rest of the images will be hidden based on their IDs and that part has been handled by the else part
//of the if statement within this loop.
for (i = 0; i < objId.length; i++) {
if (objName == objId[i]) {
obj.style.display = "block";
} else {
tempObj = document.getElementById(objId[i]);
tempObj.style.display = "none";
}
}
return;
}
<a name="isaac"></a>
<a id="one" href="#isaac" onclick="changeIt('image1');">
<img src="http://www.3cwaremarketing.com/VisiSite/wp-content/uploads/2015/05/Isaac1.jpg" border="0" alt="one" />
</a>
<a name="alan"></a>
<a id="two" href="#alan" onclick="changeIt('image2');">
<img src="http://www.3cwaremarketing.com/VisiSite/wp-content/uploads/2015/05/ed.jpg" border="0" alt="two" />
</a>
<a name="ed"></a>
<a id="three" href="#ed" onclick="changeIt('image3');">
<img src="http://www.3cwaremarketing.com/VisiSite/wp-content/uploads/2015/05/alan.jpg" border="0" alt="three" />
</a>
<a name="matt"></a>
<a id="four" href="#matt" onclick="changeIt('image4');">
<img src="http://www.3cwaremarketing.com/VisiSite/wp-content/uploads/2015/05/matt.jpg" border="0" alt="four" />
</a>
<br>
<br>
<div id="image1">
<h2>Isaac W. Jacobson</h2>
VP Business Development
<br>
<br>Mr. Jacobson brings a wealth of executive experience and professional relationships, having assembled top-tier executive teams and boards of directors for technology companies, syndicating venture capital, and buying and selling companies throughout
his career. He has held executive positions with media and technology entities such as theDial.com, Digonex Technologies, MusicRebellion, Digital Kiosk Technologies, Humanizing Technologies and eTAGZ Inc. In addition to building and growing technology
companies, Mr. Jacobson has had ownership interests across other sectors including precious metals, professional sports teams, and import/export companies working with the countries of Mexico, China, and the United Kingdom. A popular speaker and trusted
advisor to power brokers, he is often sought out by those in the highest ranks of business, politics, and entertainment to strategize on issues ranging from acquisitions, investments, and public policy to personal growth and bringing to market innovative
ideas. Mr. Jacobson is dedicated to his community, having established or served on numerous non-profit boards including the Snow College Foundation Board, the UVU Foundation Board, the Hispanic Chamber of Commerce, and the Family Defense PAC. He is
an avid donor and fundraiser for Republican political candidates and meaningful political initiatives to further Utah�s thriving business environment and family values. Mr. Jacobson is a father of three and he and his wife Tara reside in Mapleton, Utah.
</div>
<div id="image2" style="display:none">
<h2>Alan W. Bunker</h2>
CFO
<br>
<br>Mr. Bunker founded Spectrum Field Services with two other partners in 1987. A CPA and MBA, he has enjoyed an extensive career as a top executive in the public accounting, retail department store, real estate development, and health care industries.
He also has worked as an adjunct professor at the University of Utah. As a Senior Consultant with KPMG Peat Marwick in San Francisco, Mr. Bunker performed numerous consulting engagements in the savings and loan industry. He later became the Executive
Vice President and Chief Operating Officer of a real estate development firm, with major multi-family residential projects in Texas, Colorado, and Washington. Mr. Bunker has been heavily involved in the field service industry for over 20 years through
his participation with several industry-related associations. He periodically contributes articles to industry publications, and frequently has chaired committees and panels, including committees responsible for the development of field service standards
and procedures and technology advances for the industry. A long-time member of the Board of Governors of the National Association of Mortgage Field Services (NAMFS), Mr. Bunker is a past president of that organization.
</div>
<div id="image3" style="display:none">
<h2>Ed Bruno</h2>VP of Sales
<br>
<br>Mr. Bruno is an 18-year sales veteran with a performance record anchored on results. He has co-founded several start-ups, played a central role in three merger and acquisition events and lead sales teams of over 80 people to deliver on annual budgets
in excess of $400 million. His expertise crosses numerous business channels including media, technology, corporate communications, intellectual property, licensing, and webcast solutions. Mr. Bruno has held senior leadership roles including COO, CBO,
and VP of Sales in nine companies, two of them public. Mr. Bruno was voted into the �40 Under 40� by the Seattle Business Examiner. He holds Masters Degrees in English and Rhetorical Studies from Oregon State University</div>
<div id="image4" style="display:none">
<h2>A. Matthew Bunker</h2>VP Business Development
<br>
<br>Mr. Bunker is a natural-born networker and connector. He started his career as a staff member of the U.S. Senate Committee on the Judiciary in Washington, DC where he primarily focused on U.S. immigration policy but also assisted with judicial nominations
and crime legislation. Following his tenure with the Senate, Mr. Bunker continued to work with Congress with a government affairs and sports representation group. He also worked closely with the National Basketball Referees Association. Following his
career in Washington, DC, Mr. Bunker turned his attention to higher education, specifically building alumni associations. He was the Alumni Director for Salt Lake Community College, where he took their alumni activity from 32 active members to over
30,000 active members in under four years. Then he worked as the Alumni Manager with the MBA program at Brigham Young University. He organized its worldwide network of MBA alumni; focusing a great deal on social and new media, email marketing, and other
methods of connecting people together. Mr. Bunker speaks fluent Spanish. He holds a Bachelor of Arts in American Studies and Business from BYU and a Master of Public Affairs from the University of Missouri. He and his wife Jacquie are parents of four
children and they live in Saratoga Springs, Utah.</div>
<br>
I simplified your Javascript and added what was necessary to achieve what you defined as requirements. Check the snippet below. This is using vanilla Javascript only. To your images, I added a class="photo" since I assume there will also be other images on the page which should not get affected.
//An array that hold the IDs of images that we mentioned in their DIV blocks
var objId = ["image1","image2","image3","image4"];
var images = document.getElementsByClassName("photo");
function changeIt(objName) {
//The following loop does the display of a single image based on its ID. The image whose ID we passed into this function will be the
//only image that is displayed rest of the images will be hidden based on their IDs and that part has been handled by the else part
//of the if statement within this loop.
for (var i = 0; i < objId.length; i++) {
console.log(i+": "+objId[i]);
var tempObj = document.getElementById(objId[i]);
if (objName != objId[i]) {
tempObj.style.display = "none";
images[i].style.filter = "sepia(75%)";
}
else {
tempObj.style.display = "block";
images[i].style.filter = "sepia(0)";
}
}
return;
}
/* make the effect smoothly animated in browsers that support it */
img {
transition-duration: 0.4s;
}
<a name="isaac"></a>
<a id="one" href="#isaac" onclick="changeIt('image1');">
<img src="http://www.3cwaremarketing.com/VisiSite/wp-content/uploads/2015/05/Isaac1.jpg" border="0" alt="one" class="photo" />
</a>
<a name="alan"></a>
<a id="two" href="#alan" onclick="changeIt('image2');">
<img src="http://www.3cwaremarketing.com/VisiSite/wp-content/uploads/2015/05/ed.jpg" border="0" alt="two" class="photo" />
</a>
<a name="ed"></a>
<a id="three" href="#ed" onclick="changeIt('image3');">
<img src="http://www.3cwaremarketing.com/VisiSite/wp-content/uploads/2015/05/alan.jpg" border="0" alt="three" class="photo" />
</a>
<a name="matt"></a>
<a id="four" href="#matt" onclick="changeIt('image4');">
<img src="http://www.3cwaremarketing.com/VisiSite/wp-content/uploads/2015/05/matt.jpg" border="0" alt="four" class="photo" />
</a>
<br>
<br>
<div id="image1">
<h2>Isaac W. Jacobson</h2>
VP Business Development
<br>
<br>Mr. Jacobson brings a wealth of executive experience and professional relationships, having assembled top-tier executive teams and boards of directors for technology companies, syndicating venture capital, and buying and selling companies throughout
his career. He has held executive positions with media and technology entities such as theDial.com, Digonex Technologies, MusicRebellion, Digital Kiosk Technologies, Humanizing Technologies and eTAGZ Inc. In addition to building and growing technology
companies, Mr. Jacobson has had ownership interests across other sectors including precious metals, professional sports teams, and import/export companies working with the countries of Mexico, China, and the United Kingdom. A popular speaker and trusted
advisor to power brokers, he is often sought out by those in the highest ranks of business, politics, and entertainment to strategize on issues ranging from acquisitions, investments, and public policy to personal growth and bringing to market innovative
ideas. Mr. Jacobson is dedicated to his community, having established or served on numerous non-profit boards including the Snow College Foundation Board, the UVU Foundation Board, the Hispanic Chamber of Commerce, and the Family Defense PAC. He is
an avid donor and fundraiser for Republican political candidates and meaningful political initiatives to further Utah�s thriving business environment and family values. Mr. Jacobson is a father of three and he and his wife Tara reside in Mapleton, Utah.
</div>
<div id="image2" style="display:none">
<h2>Alan W. Bunker</h2>
CFO
<br>
<br>Mr. Bunker founded Spectrum Field Services with two other partners in 1987. A CPA and MBA, he has enjoyed an extensive career as a top executive in the public accounting, retail department store, real estate development, and health care industries.
He also has worked as an adjunct professor at the University of Utah. As a Senior Consultant with KPMG Peat Marwick in San Francisco, Mr. Bunker performed numerous consulting engagements in the savings and loan industry. He later became the Executive
Vice President and Chief Operating Officer of a real estate development firm, with major multi-family residential projects in Texas, Colorado, and Washington. Mr. Bunker has been heavily involved in the field service industry for over 20 years through
his participation with several industry-related associations. He periodically contributes articles to industry publications, and frequently has chaired committees and panels, including committees responsible for the development of field service standards
and procedures and technology advances for the industry. A long-time member of the Board of Governors of the National Association of Mortgage Field Services (NAMFS), Mr. Bunker is a past president of that organization.
</div>
<div id="image3" style="display:none">
<h2>Ed Bruno</h2>VP of Sales
<br>
<br>Mr. Bruno is an 18-year sales veteran with a performance record anchored on results. He has co-founded several start-ups, played a central role in three merger and acquisition events and lead sales teams of over 80 people to deliver on annual budgets
in excess of $400 million. His expertise crosses numerous business channels including media, technology, corporate communications, intellectual property, licensing, and webcast solutions. Mr. Bruno has held senior leadership roles including COO, CBO,
and VP of Sales in nine companies, two of them public. Mr. Bruno was voted into the �40 Under 40� by the Seattle Business Examiner. He holds Masters Degrees in English and Rhetorical Studies from Oregon State University</div>
<div id="image4" style="display:none">
<h2>A. Matthew Bunker</h2>VP Business Development
<br>
<br>Mr. Bunker is a natural-born networker and connector. He started his career as a staff member of the U.S. Senate Committee on the Judiciary in Washington, DC where he primarily focused on U.S. immigration policy but also assisted with judicial nominations
and crime legislation. Following his tenure with the Senate, Mr. Bunker continued to work with Congress with a government affairs and sports representation group. He also worked closely with the National Basketball Referees Association. Following his
career in Washington, DC, Mr. Bunker turned his attention to higher education, specifically building alumni associations. He was the Alumni Director for Salt Lake Community College, where he took their alumni activity from 32 active members to over
30,000 active members in under four years. Then he worked as the Alumni Manager with the MBA program at Brigham Young University. He organized its worldwide network of MBA alumni; focusing a great deal on social and new media, email marketing, and other
methods of connecting people together. Mr. Bunker speaks fluent Spanish. He holds a Bachelor of Arts in American Studies and Business from BYU and a Master of Public Affairs from the University of Missouri. He and his wife Jacquie are parents of four
children and they live in Saratoga Springs, Utah.</div>
<br>
You want to do the opposite. Instead of adding shade to other pictures, just lower their opacity.
Set all image to semi-transparent, and full opaque on hover.
On click, add an "active" class that will hold the opaque state.
$("img").click( function(){
$(this)
.addClass("active") // Adds "active" class to all images
.siblings() // Selects images other than the one that's been clicked
.removeClass("active"); // Removes the "active" class on these images
$(".text")
.hide() // Hides all texts
.eq( $(this).index() ) // select only the text corresponding to the clicked image's index
.show() // Shows only the corresponding text
})
#container{
background: #492E1D;
display: inline-block;
}
img{
opacity : 0.5;
-webkit-transition: opacity 0.4s ease-in-out;
transition: opacity 0.4s ease-in-out;
cursor: pointer;
}
img:hover, img.active{
opacity:1;
}
.text{
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<img src="http://www.lorempixel.com/150/200/people"/>
<img src="http://www.lorempixel.com/150/200/people"/>
<img src="http://www.lorempixel.com/150/200/people"/>
<img src="http://www.lorempixel.com/150/200/people"/>
</div>
<p class="text">Text for image 1</p>
<p class="text">Text for image 2</p>
<p class="text">Text for image 3</p>
<p class="text">Text for image 4</p>

AJAX: help getting xml to display in html

I'm brand new to AJAX, but I'm working on a sort of gallery. The idea is to have a number of thumbnail images and to populate a div with information from an xml file, depending on which image is pressed. I'm having a hard time getting information from my xml file to display in on my html page and would be really grateful if someone could help point me in the right direction.
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="loadXML.js" /></script>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="wrapper">
<h1>Interesting Animals</h1>
<div id="gallery">
<ul>
<li><button type="button" onClick="loadXML(0)"><img src="images/bat_thumb.png"></button></li>
<li><button type="button" onClick="loadXML(1)"><img src="images/elephant_thumb.png"></button></li>
<li><button type="button" onClick="loadXML(2)"><img src="images/bear_thumb.png"></button></li>
<li><button type="button" onClick="loadXML(3)"><img src="images/rhino_thumb.png"></button></li>
<li><button type="button" onClick="loadXML(4)"><img src="images/meerkat_thumb.png"></button></li>
</ul>
<div id="animalInfo">
<img src="images/bat.png">
<div id="animalText">
<h2 id="commonName">Giant Fruit Bat</h2>
<p><span class="description">Scientific Name: </span><span id="scientificName">Pteropus Scapulatus</span></p>
<p><span class="description">Diet: </span><span id="diet">Fruit</span></p>
<p><span class="description">Habitat: </span><span id="habitat">Southern and Southeast Asia</span></p>
<p><span class="description">Interesting Facts: </span><span id="facts">The giant fruit bat has a wing span of up to 5 feet (1.5m). It is the largest bat in the world. It has a very keen sense of smell and a very long muzzle. They roost upside down in the trees and wrap their wings around their bodies. Feeding time is at dusk when they set off to eat fruit. They squish fruit in their jaws and drink the juice but let the seeds and the rest of the fruit fall to the ground. The females give birth to one baby at a time. They will carry their baby around with them for two months.</p>
</div><!--animalText-->
</div><!--animalInfo-->
<ul>
<li><button type="button" onClick="loadXML(5)"><img src="images/koala_thumb.png"></button></li>
<li><button type="button" onClick="loadXML(6)"><img src="images/alpaca_thumb.png"></button></li>
<li><button type="button" onClick="loadXML(7)"><img src="images/platypus_thumb.png"></button></li>
<li><button type="button" onClick="loadXML(8)"><img src="images/roadrunner_thumb.png"></button></li>
<li><button type="button" onClick="loadXML(9)"><img src="images/gorilla_thumb.png"></button></li>
</ul>
</div>
</div><!--wrapper-->
</body>
</html>
Javascript:
var xmlhttp;
function loadXML() {
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else { // code for IE6-
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
changeDiv();
}
}
xmlhttp.open("GET", "animals.xml", "true");
xmlhttp.send();
}
function changeDiv() {
var xmlResponse = xmlhttp.responseXML;
root = xmlResponse.documentElement;
common = root.getElementByTagName("commonName");
scientific = root.getElementByTagName("scientificName");
food = root.getElementByTagName("diet");
environment = root.getElementByTagName("habitat");
interestingFacts = root.getElementByTagName("facts");
document.getElementById("commonName").innerHTML= common.item(1).firstChild.data;
document.getElementById("scientificName").innerHTML= scientific.item(1).firstChild.data;
document.getElementById("diet").innerHTML= food.item(1).firstChild.data;
document.getElementById("habitat").innerHTML= environment.item(1).firstChild.data;
document.getElementById("facts").innerHTML= interestingFacts.item(1).firstChild.data;
}
XML:
<?xml version="1.0"?>
<!DOCTYPE allAnimals [
<!ELEMENT allAnimals (animal+)>
<!ELEMENT animal (commonName, scientificName, diet, habitat, facts)>
<!ELEMENT commonName (#PCDATA)>
<!ELEMENT scientificName (#PCDATA)>
<!ELEMENT diet (#PCDATA)>
<!ELEMENT habitat (#PCDATA)>
<!ELEMENT facts (#PCDATA)>
]>
<allAnimals>
<animal>
<commonName>Giant Fruit Bat or Flying Fox</commonName>
<scientificName>Pteropus Scapulatus</scientificName>
<diet>Fruit</diet>
<habitat>Southern and Southeast Asia</habitat>
<facts>The giant fruit bat has a wing span of up to 5 feet (1.5m). It is the largest bat in the world. It has a very keen sense of smell and a very long muzzle. They roost upside down in the trees and wrap their wings around their bodies. Feeding time is at dusk when they set off to eat fruit. They squish fruit in their jaws and drink the juice but let the seeds and the rest of the fruit fall to the ground. The females give birth to one baby at a time. They will carry their baby around with them for two months.</facts>
</animal>
<animal>
<commonName>African Elephant</commonName>
<scientificName>Loxodonta Africana</scientificName>
<diet>Leaves, branches, and fruit</diet>
<habitat>Africa, south of the Sahara Desert</habitat>
<facts>The African Elephant is the world's largest land animal. Adult males can weigh as much as six tons. They drink more than 25 gallons (100 liters) of water each day and eat up to 650 lbs. (300kg) of food. The trunks of African elephants have two tips which they use like fingertips to pick things up. African elephant calves feed on milk for up to 18 months, and do not breed until at least 11 years old.</facts>
</animal>
<animal>
<commonName>American Black Bear</commonName>
<scientificName>Ursus Americanus</scientificName>
<diet>Vegetation, honey, insects, and fish</diet>
<habitat>North America, including northern Mexico</habitat>
<facts>These bears are often found in national parks, where they raid campsites for food. They have a keen sense of smell, and usually hunt at night. They are smaller and less dangerous than their brown bear cousins, like the Grizzly. The American Black Bear will hibernate during the winter months, but if it is disturbed it can wake up because it doesn't sleep too deeply. American black bears will avoid people, but they will defend their cubs if they feel threatened.</facts>
</animal>
<animal>
<commonName>White Rhinoceros</commonName>
<scientificName>Ceratotherium Simum</scientificName>
<diet>Grass</diet>
<habitat>Africa</habitat>
<facts>White rhinoceroses are very large. In fact, they are the second largest land animal after elephants and can weigh as much as 3.5 tons. The diet of the White Rhino is mainly made up of grass, which they find growing in large open plains. These magnificent animals have poor eyesight but exceptional hearing and a keen sense of smell. Scientists estimate that there are currently less than 7,000 white rhinos left in the wild.</facts>
</animal>
<animal>
<commonName>Meerkat</commonName>
<scientificName>Suricata Suricatta</scientificName>
<diet>Insects and birds</diet>
<habitat>Southern Africa</habitat>
<facts>Meerkats feed together during the day in groups of 20-30 individuals in dry open country. This makes them a target for predators. While some members of a meerkat group look for insects, others act as lookouts popping up on their hind legs and tails. Living in large groups helps meerkats to survive. They shelter in underground burrows.</facts>
</animal>
<animal>
<commonName>Koala</commonName>
<scientificName>Phascolarctos Cinereus</scientificName>
<diet>Eucalyptus leaves</diet>
<habitat>Eastern Australia</habitat>
<facts>Koalas are very popular animals. Often called koala bears, koalas are actually not bears at all but marsupials. They have sharp claws that allow them to climb trees to find their food. Koalas only eat eucalyptus leaves. They never need to drink water because eucalyptus leaves provide all the water they need. Female koalas have one baby at a time. The female's pouch open near the rear of her body.</facts>
</animal>
<animal>
<commonName>Alpaca</commonName>
<scientificName>Vicugna Pacos</scientificName>
<diet>Grass</diet>
<habitat>South America</habitat>
<facts>Alpacas are a domesticated descendant of guanacos. Instead of working as a pack animal, alpacas are bred and raised for their high quality wool, which is used to make yarn and other products. Some alpacas' wool grows so long that it will almost touch the ground. Alpacas feed on grass, unlike its other South American relatives which feed on bushes.</facts>
</animal>
<animal>
<commonName>Platypus</commonName>
<scientificName>Ornithorhynchus Anatinus</scientificName>
<diet>Insects and crustaceans</diet>
<habitat>Eastern Australia and Tasmania</habitat>
<facts>The platypus is one of only three species of mammals that lay eggs. It has a fur-covered body, webbed feet, and a wide beak. It looks sort of like a beaver with a bird's beak. Platypuses find their food at the bottom of the lakes and rivers where they live. They use their sensitive beak to feel for and find food. Male platypuses have a defense against predators: Their hind legs have poisonous spurs, which can leave a painful wound.</facts>
</animal>
<animal>
<commonName>Greater Roadrunner</commonName>
<scientificName>Geococcyx Californianus</scientificName>
<diet>Lizards and snakes, insects, scorpions to small rodents and small birds, hummingbirds, some fruit</diet>
<habitat>Southwestern United States and central Mexico</habitat>
<facts>The Greater Roadrunner is one of the few animals that will attack a rattlesnake. To kill this snake, the roadrunner grabs the snake just behind the head, then it hits it against the ground or rocks. Roadrunners live in pairs, defending their area all year.</facts>
</animal>
<animal>
<commonName>Western Gorilla</commonName>
<scientificName>Gorilla Gorilla</scientificName>
<diet>Leaves</diet>
<habitat>Western and Central Africa</habitat>
<facts>Gorillas are the largest of the great apes. Great apes can stand on their hind legs. They are also very good with their hands and can use wooden sticks like tools. Gorillas live in groups of up to 20 animals. They eat in the trees and on the ground.</facts>
</animal>
</allAnimals>
Declare xmlhttp variable outside the loadXML() function to make it global so you will be able to access it in changeDiv() function:
var xmlhttp;
function loadXML() { ... }
function changeDiv() { ... }
Other solution is to send it as an argument of changeDiv().
function loadXml() {
...
changeDiv(xmlhttp);
...
}
function changeDiv(xmlhttp) { ... }

Categories

Resources