Hell,
I have the html code below:
<div class="row">
<button id="dog-btn">Show Dog</button>
<br>
</div>
<div id="pets">
</div>
I want some simple code that uses JS to check if the pets div is visible. If it is, the inner text of dog-btn should read Hide Dog. If not visible, it should read Show Dog.
Let me know!
You can get this by using the .style.display() DOM method.
HTML
<div class="row">
<button id="dog-btn" onclick="showDog()">Show Dog</button>
<br>
</div>
Dog
JS
document.getElementById("pets").style.display = "none";
function showDog() {
var petDiv = document.getElementById("pets");
var petBtn = document.getElementById("dog-btn");
if (petDiv.style.display == "none") {
petBtn.innerHTML = "Hide Dog";
petDiv.style.display = "block"
}
else {
petBtn.innerHTML = "Show Dog";
petDiv.style.display = "none"
}
}
#DemoNemo5 's answer technically does what your question asks, but i'll assume that you want a button that toggles hiding and showing. Also the previous answer only changes the button once whenever that piece of code is ran.
function togglePets(){
if(document.getElementById("pets").style.display != "none"){
document.getElementById("dog-btn").innerHTML = "Show Dog";
document.getElementById("pets").style.display = "none";
console.log("hide")
} else {
document.getElementById("dog-btn").innerHTML = "Hide Dog";
document.getElementById("pets").style.display = "block";
console.log("show")
}
}
<div class="row">
<button id="dog-btn" onclick="togglePets()">Hide Dog</button>
<br>
</div>
<div id="pets">
stuff
</div>
we make a function that's called every time the button is clicked, the function checks if the style.display is none (which means it's hidden) and changes the text ofthe button and toggles the display of the pets div
const dog_btn = document.querySelector("#dog-btn");
const pets = document.querySelector("#pets");
dog_btn.addEventListener("click", ()=> {
pets.style.display = pets.style.display !== "none" ? "none" : "initial";
dog_btn.innerText = pets.style.display !== "none" ? "Hide Dog" : "Show Dog";
});
<div class="row">
<button id="dog-btn">Hide Dog</button>
<br>
</div>
<div id="pets">
Something
</div>
You can get the div using document.getElementById() in order to access its styles. This code assumes you're toggling the CSS display property.
if(document.getElementById("pets").style.display == "none"){
document.getElementById("dog-btn").innerHTML = "Show Dog";
} else {
document.getElementById("dog-btn").innerHTML = "Hide Dog";
}
<div class="row">
<button id="dog-btn">Show Dog</button>
<br>
</div>
<div id="pets">
</div>
Related
I wanted to make a content of a div to get displayed once another div is clicked. But I have tried this :
function loadFishContent() {
if (div is clicked) {
document.getElementById('fish').style.display = "block";
document.getElementById('dogs').style.display = "none";
document.getElementById('cats').style.display = "none";
}
};
I have tried:
if (document.getElementByID('menu-fish') == true) {
//do action
}
But the action is applied in all the div I clicked.
My html is :
<div id="menu-fish" onclick="loadFishContent()"> Fish </div>
<div id="menu-dogs" onclick="loadDogsContent()"> Dogs </div>
<div id="menu-cats" onclick="loadCatsContent()"> Cats </div>
<div id="content">
<div id="fish">
<h2> Fish </h2>
<img src="fish.jpg"/>
<p> Information about fish in the store goes here.</p>
</div>
<div id="dogs">
<h2> Dogs </h2>
<img src="dog.jpg" />
<p> Information about dogs in the store go here.</p>
</div>
<div id="cats">
<h2> Cats </h2>
<img src="cat.jpg" />
<p> Information about cats in the store go here.</p>
</div>
</div>
Thing is, how do I target the div which is clicked in the if condition?
As you called 3 different methods in your html code, you have to write 3 javascript functions.
Then you can write code to show and hide div without check of which div clicked, because every div click have different methods to call.
If you wish to do that with a single js method as
function loadContent(id) {
if (id=='fish') {
document.getElementById('fish').style.display = "block";
document.getElementById('dogs').style.display = "none";
document.getElementById('cats').style.display = "none";
}
else if (id=='dogs') {
document.getElementById('fish').style.display = "none";
document.getElementById('dogs').style.display = "block";
document.getElementById('cats').style.display = "none";
}
else if (id=='cats') {
document.getElementById('fish').style.display = "none";
document.getElementById('dogs').style.display = "none";
document.getElementById('cats').style.display = "block";
}
};
And call that in html as
<div id="menu-fish" onclick="loadContent('fish')"> Fish </div>
<div id="menu-dogs" onclick="loadContent('dogs')"> Dogs </div>
<div id="menu-cats" onclick="loadContent('cats')"> Cats </div>
Just suggesting cleaner switch approach to an existing answer by crack_iT
function loadContent(id) {
document.getElementById('dogs').style.display = "none";
document.getElementById('cats').style.display = "none";
document.getElementById('fish').style.display = "none";
switch (id){
case 'fish': document.getElementById('fish').style.display = "block";
break;
case 'cats': document.getElementById('cats').style.display = "block";
break;
case 'dogs': document.getElementById('dogs').style.display = "block";
break;
}
};
Its a bit more smaller and looks cleaner and easier to understand;
Approach 1:
Update your HTML like below:
<div id="menu-fish" onclick="loadContent('fish')"> Fish </div>
<div id="menu-dogs" onclick="loadContent('dogs')"> Dogs </div>
<div id="menu-cats" onclick="loadContent('cats')"> Cats </div>
And Update your function as below:
function loadContent(divid) {
document.getElementById('fish').style.display = "none";
document.getElementById('dogs').style.display = "none";
document.getElementById('cats').style.display = "none";
document.getElementById(divid).style.display = "block"
}
Approach 2:
If you want id of the div in function then update your HTML like below:
<div id="menu-fish" onclick="loadContent(this)"> Fish </div>
<div id="menu-dogs" onclick="loadContent(this)"> Dogs </div>
<div id="menu-cats" onclick="loadContent(this)"> Cats </div>
And Update your function as below:
function loadContent(div) {
var divid = div.id;
document.getElementById('fish').style.display = divid == 'menu-fish' ? 'block' : "none";
document.getElementById('dogs').style.display = divid == 'menu-dogs' ? 'block' : "none";
document.getElementById('cats').style.display = divid == 'menu-cats' ? 'block' : "none";
}
You should avoid using if/else as it will be problematic code to manage with 100's of content types.
Use document.querySelectorAll
/* Create only 1 function for all the content types - pass id as parameter */
function loadContent(id) {
// Use querySelectorAll to all first level div's, to hide all
document.querySelectorAll("div#content > div").forEach(el => el.style.display = "none");
// Now, display the clicked content type
document.getElementById(id).style.display = "block";
}
div#content > div {
display: none;
}
<div id="menu-fish" onclick="loadContent('fish')"> Fish </div>
<div id="menu-dogs" onclick="loadContent('dogs')"> Dogs </div>
<div id="menu-cats" onclick="loadContent('cats')"> Cats </div>
<div id="content">
<div id="fish"><h2> Fish </h2><img src="fish.jpg"/><p> Information about fish in the store goes here.</p></div>
<div id="dogs"><h2> Dogs </h2><img src="dog.jpg" /><p> Information about dogs in the store go here.</p></div>
<div id="cats"><h2> Cats </h2><img src="cat.jpg" /><p> Information about cats in the store go here.</p></div>
</div>
Managed to get the words to appear when a certain button is pressed thanks to you guys. Just need help with one more thing. I've tried using google, only found some ideas, but wasn't working well. This is just something simple.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<article>
<!-- insert clickable box here -->
<p id="q1">Want to play a game?</p>
<br>
<button type="button" onclick="buttonYes1()" id="byes1">Yes</button>
<button type="button" onclick="buttonNo1()" id="bno1">No</button>
<script type="text/javascript">
function buttonYes1() {
document.getElementById("yes").style.display = "block";
}
// code to hide first question after yes button is pressed
var button = document.getElementById('byes1')
button.addEventListener('click', hideshow, false);
function byes1() {
document.getElementById('byes1').style.display = 'block';
this.style.display = 'none'
}
function buttonNo1() {
document.getElementById("no").style.display = "block";
}
</script>
<!-- if yes, show detailed message -->
<p id="yes" style="display: none;">random words</p>
<!-- if no, show thanks for playing -->
<p id="no" style="display: none;">no words</p>
<!-- if yes, followed by detailed message, insert question #2 here -->
<p id="q2">Qusetion number 2 goes here</p>
<button type="button" onclick="buttonYes2()">Yes</button>
<button type="button" onclick="buttonNo2()">No</button>
<script type="text/javascript">
function buttonYes2() {
document.getElementById("yes2").style.display = "block";
}
function buttonNo2() {
document.getElementById("no2").style.display = "block";
}
</script>
<!-- if yes to question #2, give instructions on what to do -->
<p id="yes2" style="display: none;">random words 2</p>
<!-- if no to question #2, order soda, game ends -->
<p id="no2" style="display: none;">no words 2</p>
</article>
So my question here is, how can I get the first question to disappear once the "yes" button is pressed? On top of that, I want to hide the second question until the user clicks on the "yes" button and that's when the question appears.
Is this what you are asking for? See the snippet below:
function buttonYes1() {
var Yes1 = document.getElementById("yes")
Yes1.style.display = "block";
var question1Div = document.getElementById("question1Div")
question1Div.style.display = "none";
var question2Div = document.getElementById("question2Div")
question2Div.style.display = "block";
}
// code to hide first question after yes button is pressed
var button = document.getElementById('byes1')
button.addEventListener('click',false);
function byes1() {
document.getElementById('byes1').style.display = 'block';
this.style.display = 'none'
}
function buttonNo1() {
document.getElementById("no").style.display = "block";
}
function buttonYes2() {
document.getElementById("yes2").style.display = "block";
}
function buttonNo2() {
document.getElementById("no2").style.display = "block";
}
<article>
<div id="question1Div">
<!-- insert clickable box here -->
<p id="q1">Want to play a game?</p>
<br>
<button type="button" onclick="buttonYes1()" id="byes1">Yes</button>
<button type="button" onclick="buttonNo1()" id="bno1">No</button>
</div>
<!-- if yes, show detailed message -->
<p id="yes" style="display: none;">random words</p>
<!-- if no, show thanks for playing -->
<p id="no" style="display: none;">no words</p>
<!-- if yes, followed by detailed message, insert question #2 here -->
<div id="question2Div" style="display:none;">
<p id="q2">Qeustion number 2 goes here</p>
<button type="button" onclick="buttonYes2()">Yes</button>
<button type="button" onclick="buttonNo2()">No</button>
</div>
<!-- if yes to question #2, give instructions on what to do -->
<p id="yes2" style="display: none;">random words 2</p>
<!-- if no to question #2, order soda, game ends -->
<p id="no2" style="display: none;">no words 2</p>
</article>
This is where you are going to have to put on your thinking cap as a programmer and start coming up with solutions. Here is one way of doing this:
var questionElements = document.getElementsByClassName('question');
var currentQuestion = 1;
function answerQuestion(answer){
//Handle the response
switch(answer) {
case 'Yes':
//Do something here
break;
case 'No':
//Do something else here
break;
default:
console.log('Oops, how did you get here?');
}
//Display or remove each question
[].forEach.call(questionElements, (qElement, index) => {
if (index == currentQuestion - 1) {
//Remove the answered question
qElement.style.display = 'None';
} else if (index == currentQuestion) {
//Display the next question
qElement.style.display = 'Block';
}
});
//Prepare for the next question
currentQuestion++;
if (currentQuestion == questionElements.length) {
//All finished, Do something
}
}
.question {
display: none;
}
.question:first-of-type {
display: block;
}
<div class="question">
<p>Question 1: Do you like eggs?</p>
</div>
<div class="question">
<p>Question 2: Do you like ham?</p>
</div>
<div class="question">
<p>Question 3: Do you like green eggs and ham?</p>
</div>
<button onclick="answerQuestion('Yes');">Yes</button>
<button onclick="answerQuestion('No');">No</button>
I'm trying to use an onclick event with an anchor tag that will change the innerHTML of another element on the page. I'm not sure what I'm doing wrong, so all the code I'm using is below. I hope you guys can point out my mistake and tell me what it was I misunderstood. The JavaScript file is included after the body, but you can see that on the JSfiddle here. So, when I click Settings, I want the BookmarkList div to show it's own HTML code, and the same for Home. The BookmarkList div will be the center of attention for this site. I'm just not sure what I'm doing wrong for this.
HTML:
<body id="bodyBG">
<div class="wrapper">
<div class="box header">
Header
</div>
<div class="box content">
<div class="box subcontent1">
<div class="sdfgsdfgsdfg"><input id="categoryName" placeholder="Category Name"></input></div>
<div class="sdfgsdfg"><input id="urlLink" placeholder="Site Address"></input></div>
<div class="sdfgsddfg"><input id="bookmarkName" placeholder="Bookmark Name"></input></div>
<div><button>Save</button></div>
<hr>
<input placeholder="Search Bookmarks"></input>
<button>Search</button>
</div>
<div class="box subcontent2">
Settings
<hr>
Home
Back
Forwards
</div>
<div id="bookmarkList" class="box subcontent3 bookmark-list">
</div>
</div>
<div class="box footer">Footer</div>
</div>
<script src="assets/js/bookmark-action-script.js"></script>
</body>
JavaScript:
var settingsNav = document.getElementById('settingsNav');
var homeNav = document.getElementById('homeNav');
var changeThis = document.getElementById("bookmarkList");
function myFunction(this) {
if (this === settingsNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr>";
}
else if (this === homeNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr><p>Store all your bookmarks here!</p><ul><li>An secure storage means for your privacy needs!</li><li>24/7 Availability</li></ul>";
}
else (this != settingsNav | homeNav) {
changeThis.innerHTML = "Nothing to see here!";
}
};
document.getElementById("settingsNav").addEventListener("click");
document.getElementById("homeNav").addEventListener("click");
The Solution:
I always add the solution that was appropriate for my problems, so future observers can see what issue I had and what the solution was. My issue was not adding the function to my eventlistener. You do not need to specify onclick events inside the HTML code if you specify event listeners with accompanying functions in your JavaScript code. But without the functions tied to the eventlisteners, nothing will happen. I understand that now.
var settingsNav = document.getElementById('settingsNav');
var homeNav = document.getElementById('homeNav');
var changeThis = document.getElementById("bookmarkList");
function myFunction(event) {
var el = this;
if (el === settingsNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr>";
} else if (el === homeNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr><p>Store all your bookmarks here!</p><ul><li>A secure storage means for your privacy needs!</li><li>24/7 Availability</li></ul>";
} else if (el != settingsNav || homeNav) {
changeThis.innerHTML = "Nothing to see here!";
}
};
document.getElementById("settingsNav").addEventListener("click", myFunction);
document.getElementById("homeNav").addEventListener("click", myFunction);
Remove attribute event handlers from HTML. Change function (this) to function (event). You did not add an event handler at.addEventListener()call, where you can passmyFunction` as a reference to to function to call when event is dispatched.
OR in JavaScript should be || instead of | at second else..if
Note, <input> element is self-closing, </input> is invalid HTML.
<body id="bodyBG">
<div class="wrapper">
<div class="box header">
Header
</div>
<div class="box content">
<div class="box subcontent1">
<div class="sdfgsdfgsdfg"><input id="categoryName" placeholder="Category Name"></div>
<div class="sdfgsdfg"><input id="urlLink" placeholder="Site Address"></div>
<div class="sdfgsddfg"><input id="bookmarkName" placeholder="Bookmark Name"></div>
<div><button>Save</button></div>
<hr>
<input placeholder="Search Bookmarks">
<button>Search</button>
</div>
<div class="box subcontent2">
Settings
<hr>
Home
Back
Forwards
</div>
<div id="bookmarkList" class="box subcontent3 bookmark-list">
</div>
</div>
<div class="box footer">Footer</div>
</div>
<script>
var settingsNav = document.getElementById('settingsNav');
var homeNav = document.getElementById('homeNav');
var changeThis = document.getElementById("bookmarkList");
function myFunction(event) {
var el = this;
if (el === settingsNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr>";
} else if (el === homeNav) {
changeThis.innerHTML = "<h3>Bookmarks</h3><hr><p>Store all your bookmarks here!</p><ul><li>An secure storage means for your privacy needs!</li><li>24/7 Availability</li></ul>";
} else if (el != settingsNav || homeNav) {
changeThis.innerHTML = "Nothing to see here!";
}
};
document.getElementById("settingsNav").addEventListener("click", myFunction);
document.getElementById("homeNav").addEventListener("click", myFunction);
</script>
</body>
Your code works fine in Chrome by fixing couple of syntax errors.
update else to else if
else if (clk != settingsNav | homeNav)
update this parameter to something else in myFunction
function myFunction(clk)
no need to add event since you called myFunction in onclick, so remove:
document.getElementById("settingsNav").addEventListener("click");
document.getElementById("homeNav").addEventListener("click");
Somehow it didn't work in jsfiddler.
I'm building an about us page and I'm hoping to use JavaScript to show/hide/replace a DIV's content with a vision statement or a bio depending on which is clicked by the user. I'm brand new to using script, so I'm hoping there is someone who has done this before.
I currently have a button for the bio and one for the vision and while I'm able to show and hide text with no problem I have no clue how to replace the DIV so that the Bio and Vision don't show at the same time.
Here is what I have so far:
function showhide(id) {
var e = document.getElementById(id);
e.style.display = (e.style.display == 'block') ? 'none' : 'block';
}
<button type="button" onclick="javascript:showhide('vision')">Vision</button>
<button type="button" onclick="javascript:showhide('bio')">Bio</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
I'd also like the button text to change to "Hide Bio" or "Hide Vision" depending on which is revealed as well.
If anyone could help with this it would be GREATLY appreciated for a Java Noob like me.
This is also my first time using a forum like this so any pointers or feedback is appreciated...gotta start somewhere, right?
UPDATE - I attached an image to give a better idea of what I'm try to accomplish.
There are a couple of issues with logic. If you show/hide one div, you'll still need to hide/show the second div. So you can either add more lines of code to do that.. or simply you can use one div and update its content based on the button clicked.
so you can try this:
<script>
var textStrings = {"author1": {"Vision":"this is author1 vision", "Bio":"this is author1 bio"},
"author2": {"Vision":"this is author2 vision", "Bio":"this is author2 bio"},
"author3": {"Vision":"this is author3 vision", "Bio":"this is author3 bio"}};
function showhide(element) {
reset();
var id=element.id;
var author = document.getElementById("authors").elements["authors"].value;
var flag = document.getElementById('content').innerHTML == textStrings[author][id];
document.getElementById('content').innerHTML = flag ? "" : textStrings[author][id];
element.innerHTML = flag ? id : "hide " + id;
}
function reset(){
for (var k in textStrings["author1"]){
document.getElementById(k).innerHTML = k;
}
}
function resetAuthor(){
document.getElementById('content').innerHTML = ""
reset();
}
</script>
<form id="authors">
<input type="radio" name="authors" id="author1" onchange="resetAuthor()" value="author1" checked> author 1
<input type="radio" name="authors" id="author2" onchange="resetAuthor()" value="author2"> author 2
<input type="radio" name="authors" id="author3" onchange="resetAuthor()" value="author3"> author 3
</form>
<div style="display:inline">
<button type="button" id="Vision" onclick="javascript:showhide(this)">Vision</button>
<button type="button" id="Bio" onclick="javascript:showhide(this)">Bio</button>
</div>
<div style="display: block;">
<p id="content"></p>
</div>
This code also toggles/set contents as empty if you hit the button again.
DEMO
Try to pass the this object into the inline event handler and check the content's display state to toggle the button's text,
HTML:
<button type="button" onclick="javascript:showhide('vision',this)">Vision</button>
<button type="button" onclick="javascript:showhide('bio',this)">Bio</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
JS
function showhide(id,elem) {
var e = document.getElementById(id);
var cond = (e.style.display == 'block');
e.style.display = cond ? 'none' : 'block';
elem.textContent = (id == "vision") ? (cond ? "Show Vision" : "Hide Vision")
: (cond ? "Show Bio" : "Hide Bio");
}
DEMO
Try this out.
var prevPage = "";
var currPage = "";
function showhide(event) {
prevPage = currPage;
currPage = event.id.split("_")[1];
if(prevPage !== currPage){
showEle(currPage);
if(prevPage !== ''){
hideEle(prevPage);
}
} else {
toggle(currPage);
}
}
function toggle(id){
var curr = document.getElementById(id);
if(curr.style.display === 'block'){
curr.style.display = 'none';
updateBtn('btn_'+id, 'Show');
} else {
curr.style.display = 'block';
updateBtn('btn_'+id, 'Hide');
}
}
function updateBtn(id, newStr){
var btn = document.getElementById(id);
btn.innerHTML = newStr + ' ' + btn.innerHTML.split(' ')[1];
}
function showEle(id){
document.getElementById(id).style.display = 'block';
updateBtn('btn_'+id, 'Hide');
}
function hideEle(id){
document.getElementById(id).style.display = 'none';
updateBtn('btn_'+id, 'Show');
}
<button id="btn_vision" type="button" onclick="showhide(this)">Show Vision</button>
<button id="btn_bio" type="button" onclick="showhide(this)">Show Bio</button>
<button id="btn_xyz" type="button" onclick="showhide(this)">Show Xyz</button>
<button id="btn_abc" type="button" onclick="showhide(this)">Show Abc</button>
<div id="vision" style="display: none;">
<p>This is my vision</p>
</div>
<div id="bio" style="display: none;">
<p>This is my bio</p>
</div>
<div id="xyz" style="display: none;">
<p>This is my xyz</p>
</div>
<div id="abc" style="display: none;">
<p>This is my abc</p>
</div>
Note: You might want to initialize the currPage with the first page's id since it gives a better feel.
Say currPage = "vision" and also make display block for div id = "vision".
Oke, so I am trying to create an interactive menu.
Now I am really struggling to make the JavaScript access the child nodes of a div and change a specific css element.
The html code goes as follow:
<div id="navbar">
Control panel
<div class="button" onclick="openMe(self);">
Users
<div class="sub-button">
Profile
</div>
<div class="sub-button">
Ban
</div>
</div>
<div class="button">
Roles
<div class="sub-button">
Profile
</div>
<div class="sub-button">
Ban
</div>
</div>
</div>
And the JavaScript is :
function openMe(a)
{
child = a.document.getElementsByClassName('sub-button');
console.log("a is "+a);
console.log("child is "+$(child).get());
console.log(self);
for (i = 0; i < child.length; i++){
//
console.log("Key "+i+" is "+child[i]);
console.log("Display for "+i+" is "+child[i].style.display);
if (child[i].style.display == "" || child[i].style.display == "none"){
child[i].style.display = "block";
} else {
child[i].style.display = "none";
}
}
}
In the css sub-button is hidden.
Now I have been trying to google, but I haven't found anything even close.
How can I make it that if I press button, the sub-buttons within button change css elements?
gr,
Angels
edit :
jsfiddle http://jsfiddle.net/r7tzr6dm/
The error is in the first line. When you would open the error console, a error message will occur.
Change the line a.document.getElementsByClassName('sub-button'); to a.getElementsByClassName('sub-button');.
The second error is change onclick="openMe(self); to onclick="openMe(this);.