<p>This button will alternate different peoples names every time you click it.</p>
<button class="personNameButton">
Get Person's Name
</button>
<div class="personNameDisplay">-no name found-</div>
var currentPerson;
var person1 = {
id: 0,
name: "Brenton Strine",
photo: "img_29483.jpg",
allergies:
"Eggplant",
};
var person2 = {
id:
1,
name: "tim Hare",
photo:
"img_34749.jpg",
allergies:
"unknown",
};
var nameButton = document.querySelector(".personNameButton");
var nameDisplay = document.querySelector(".personNameDisplay");
// Set up click handler
nameButton.addEventListener("click", function(e){
switchCurrentPerson();
var personsName = getName(currentPerson);
nameDisplay.innerText = personsName;
});
// return the name of the current person
var getName = function (person) {
if (person.name) {
return
person.name;
} else if (person.firstName && person.lastName) {
return person.firstName + " " + person.lastName;
}
}
// function to switch the current person to a different person
var switchCurrentPerson = function() {
if (currentPerson && currentPerson.id === 0) {
currentPerson =
person2;
} else {
currentPerson =
person1;
}
};
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.