Making a button that shows a hidden image on click - javascript

I've found tutorials that make an image hidden with some css, javascript and html but I'm having trouble making the image hidden first, and then having the button be able to make it visible and then hidden if pressed again.
edit: hopefully this code should help! Again, sorry I can't figure some of this out, I don't really know how this site works and I'm pretty new to coding,,,,
edit 2: I added where the function is being called. It's suppose to be a multiple choice that shows an image when correct!
<style>
div.notdropdown {
margin-top: 100px;
margin-bottom: 100px;
border: 1px solid black;
background-color: rgb(181, 204, 180, 0.9);
}
.hide{
display:none;
}
</style>
</body>
<script>
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<div id="myDIV">
<img class= "hide" src="https://www.merriam-webster.com/assets/mw/static/art/dict/frig_bi.gif">
<br>
<a class= "hide" href="https://www.merriam-webster.com/dictionary/frigate%20bird">https://www.merriam-webster.com/dictionary/frigate%20bird </a>
<br>
</div>
<h1>What is a Frigate?</h1><br>
<form >
<input type="radio" name="choice" value="Bird"> A type of Bird
<input type="radio" name="choice" value="Mangrove"> A type of Mangrove tree
<input type="radio" name="choice" value="Sea Creature"> A type of Sea Creature
<input type="radio" name="choice" value="None"> None of These
</form>
<button onclick="submitAnswer();"> Submit Answer</button>
</body>
<script>
function submitAnswer() {
var radios = document.getElementsByName("choice");
var i = 0, len = radios.length;
var checked = false;
var userAnswer;
for( ; i < len; i++ ) {
if(radios[i].checked) {
checked = true;
userAnswer = radios[i].value;
}
}
if(!checked) {
alert("please select choice answer");
return;
}
// Correct answer
if(userAnswer === "Bird") {
myFunction();
alert("Answer is correct!");
}
// incorrect answer
else {
alert("Answer is wrong!");
}
}
</script>
</body>
</html>

in fact it's very simple, just use the toggle method, which allows you to easily enable and disable a class in an element
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<button onClick="toggleImage()" class="w-100 mb-10">Show/Hide</button>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>
to work with a link to just change the tag to a and use href="#"
function toggleImage(){
document.querySelector('#image').classList.toggle('hidden');
}
.hidden{
display: none;
}
.w-100{
width: 100%;
}
.mb-10{
margin-bottom: 10px;
}
<a onClick="toggleImage()" class="w-100 mb-10" href="#">Show/Hide</a>
<img src="https://images.pexels.com/photos/462118/pexels-photo-462118.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500" id="image" class="hidden w-100"/>

You just need to call your function on button tag. Add a button in your html file on which you want your div to toggle. As you are using function name myFunction, call it on that function using
onClick="myFunction()"
And your code should work fine. Don't need to add any new class or even hide your div by default.

check this code. I think this will help you.
<button id = "showhide" onclick = "showhide()">Show Hide Image</button>
<div id = "image" style="width: 100px; height : 100px;">
<h4> Image Code </h4>
</div>
<script>
$('#showhide').on('click', function(e){
$("#image").toggle();
});
</script>

Related

How to separete div blocks with the same class but diffent features

Good day!
I have a pop-up section. There are 2 div blocks in it with identical structure. The idea is to have 2 buttons (one is to edit a profile the other is to create a new card with some info) that will call this pop-up, but i need to track which one is called. The popup itself has a darker background compare to main page and a form. I have thought of a modifier popup__container_type_(edit/create) that has a display: none command so when i toggle it it the popup would appear with the right form. Most likely my logic was mistaken. I dont know how to distiguish them (div blocks) correctly.
Another problem is that closebutton seems to work for one form only.
Any help would be great!
HTML:
<section class="popup">
<div class="popup__container popup__container_type_edit">
<button type="button" class="popup__cancelbutton"></button>
<form class="popup-form" name="form">
<h2 class="popup-form__title">Header 1</h2>
<input type="text" class="popup-form__input popup-form__input_type_name" name="name">
<input type="text" class="popup-form__input popup-form__input_type_job" name="job">
<button type="submit" class="popup-form__savebutton">Save</button>
</form>
</div>
<div class="popup__container popup__container_type_create">
<button type="button" class="popup__cancelbutton"></button>
<form class="popup-form" name="form">
<h2 class="popup-form__title">Header 2</h2>
<input type="text" class="popup-form__input popup-form__input_type_place" placeholder="Name of the place" name="place">
<input type="text" class="popup-form__input popup-form__input_type_imagelink" placeholder="Image link" name="imagelink">
<button type="submit" class="popup-form__savebutton">Create</button>
</form>
</div>
</section>
JS:
let popUpSection = document.querySelector(`.popup`);
let cancelButton = popUpSection.querySelector(`.popup__cancelbutton`);
let popUpContainer = popUpSection.querySelector(`.popup__container`);
let formElement = popUpSection.querySelector(`.popup-form`);
let newInputName = popUpSection.querySelector(`.popup-form__input_type_name`);
let newInputJob = popUpSection.querySelector(`.popup-form__input_type_job`);
let inputName = document.querySelector(`.profile-info__title`);
let inputJob = document.querySelector(`.profile-info__text`);
let editButton = document.querySelector(`.profile-info__editbutton`);
let createButton = document.querySelector(`.profile__addbutton`);
//Open / close popup section
let formTogglePopUp = () => {
if (!popUpSection.classList.contains(`popup_acitve`)){
//Autofill
newInputName.value = inputName.textContent;
newInputJob.value = inputJob.textContent;
}
popUpSection.classList.toggle(`popup_active`);
}
//Save input changes
function popUpFormSaved (event) {
event.preventDefault();
inputName.textContent = newInputName.value;
inputJob.textContent = newInputJob.value;
formTogglePopUp();
}
formElement.addEventListener('submit', popUpFormSaved);
cancelButton.addEventListener('click', formTogglePopUp);
editButton.addEventListener('click', formTogglePopUp);
createButton.addEventListener(`click`, formTogglePopUp);
CSS:
.popup__container
{
display: block; *by default*
}
.popup__container_type_(edit/create)
{
display: none;
}
.popup
{
display:none;
}
.popup__active
{
display: flex;
}
You can do it with js, set ids and use them instead of class, it's more easy.
function popUpEdit() {
document.getElementById("popUp").style.display = "block";
document.getElementById("popUpEdit").style.display = "block";
}
function popUpCreate() {
document.getElementById("popUp").style.display = "block";
document.getElementById("popUpCreate").style.display = "block";
}
#popUp, #popUpEdit, #popUpCreate {
display: none;
}
<div class="smt">
Hello
<button onclick="popUpEdit()">Edit</button>
</div>
<div class="smt">Hello
<button onclick="popUpCreate()">Create</button>
</div>
<section id="popUp">
<div>popUp</div>
<div id="popUpEdit">Edit-popup</div>
<div id="popUpCreate">Create-popup</div>
</section>
Generaly, I do that this way:
const SectionPopUp = document.querySelector('section.popup')
function show(elm)
{
SectionPopUp.classList.toggle('Create','Create'===elm)
SectionPopUp.classList.toggle('Edit','Edit'===elm)
}
section.popup,
section.popup.Edit > div:not(.popup__container_type_edit),
section.popup.Create > div:not(.popup__container_type_create) {
display:none;
}
section.popup.Edit,
section.popup.Create {
display:block;
}
/* cosmetic part, just for testing here */
section.popup > div {
border : 1px solid aqua;
padding : .6em;
margin : 1em;
width : 15em;
}
div.popup__container_type_create {
border-color: orange !important;
}
<button onclick="show('Edit')"> show Edit </button>
<button onclick="show('Create')"> show Create </button>
<button onclick="show('')"> show none </button>
<section class="popup">
<div class="popup__container popup__container_type_edit">
pop-up edit content
</div>
<div class="popup__container popup__container_type_create">
pop-up create content
</div>
</section>

What's a simple, non-jquery way to toggle between two divs using two buttons?

I'm looking for a simple, non-jquery method of toggling between two divs. Specifically, clicking button A will show div A content (and hide div B content), and clicking button B will show div B content (and hide div A content. I want div A content to appear by default when the page loads.
The code I have isn't hiding the appropriate divs from the onclick
I've looked around, but every solution seems overly complex or seems to involve jquery - which I would really prefer not to use, because I have to work with an old jquery library on a site where I shouldn't be updating that stuff.
<button class="button" onclick="content_A(); Hide_Content_B;">Content A</button>
<button class="button" onclick="content_B(); Hide_Content_A;">Content B</button>
<script>
function Content_A() {
var x = document.getElementById("A");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<script>
function Hide_Content_B() {
var x = document.getElementById("B");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
</script>
<script>
function Content_B() {
var x = document.getElementById("B");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
<script>
function Hide_Content_A() {
var x = document.getElementById("A");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
</script>
<div id="A"> stuff</div>
<div id="B"> other stuff </div>
Create one function showContent that takes the id of the element you want
to toggle as parameter and just toggles a CSS class, i.e visible on the element with that id.
Use CSS classes to initially hide the "toggleable" elements. You can set the visible class directly on the element you want shown on page load.
Here's an example:
function showContent(id) {
document.getElementById(id).classList.toggle('visible')
}
/*
All elements with class "toggleable"
should be hidden.
*/
.toggleable {
display: none;
}
/*
All elements that have both
class "toggleable" and "visible"
should be visible.
*/
.toggleable.visible {
display: block;
}
<button onclick="showContent('a');" >Show Content A</button>
<button onclick="showContent('b');" >Show Content B</button>
<div class="toggleable visible" id="a">
Hello Content A!
</div>
<div class="toggleable" id="b">
Hello Content B!
</div>
About your code:
You have to call the function using parenthesis like Hide_Content_A() and Hide_Content_B(); which are misssing in onclick of the <button>
The functions Content_B and Content_B start with uppercase C.
The fix your own code, just run Hide_Content_B(); at the end to hide the second one.
Note that you can also use a single <script> block.
function Content_A() {
var x = document.getElementById("A");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function Hide_Content_B() {
var x = document.getElementById("B");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
function Content_B() {
var x = document.getElementById("B");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
function Hide_Content_A() {
var x = document.getElementById("A");
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "none";
}
}
Hide_Content_B();
<button class="button" onclick="Content_A(); Hide_Content_B();">Content
A
</button>
<button class="button" onclick="Content_B(); Hide_Content_A();">Content
B
</button>
<div id="A"> stuff</div>
<div id="B"> other stuff</div>
If you dont want to use jQuery, you should consider not using javascript at all.
You can do the same with pure css. Also the styling of button tags some times brakes in other devices, so I suggest to use tag or just a span
Here is a pure CSS solution:
input {
display:none;
}
input[name="toggle"] + .toggleContent{
max-height: 0;
overflow: hidden;
transition: max-height .4s;
}
input[name="toggle"]:checked + .toggleContent{
max-height: 100px;
}
<label for="A">A Button</label>
<input type="radio" name="toggle" value="1" id="A" checked="checked">
<div class="toggleContent">This is content for A</div>
<label for="B">B Button</label>
<input type="radio" name="toggle" value="2" id="B">
<div class="toggleContent">This is content for B</div>
Here's a simple solution that requires jQuery 1.7 or above, since you mentioned that you're working with an old jQuery library!
$(document).on('click', '.map-point-sm', function() {
var show = $(this).data('show');
$(show).removeClass("hide").siblings().addClass("hide");
});
.hide {
display: none;
}
.map-container {
text-align: center;
}
button{
width: 5%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<div class="map-container">
<div class="inner-basic division-map div-toggle" data-target=".division-details" id="divisiondetail">
<button class="map-point-sm" data-show=".a">
<div class="content">
<div class="centered-y">
<p>A</p>
</div>
</div>
</button>
<button class="map-point-sm" data-show=".b">
<div class="content">
<div class="centered-y">
<p>B</p>
</div>
</div>
</button>
</div>
</div>
<div class="map-container">
<div class="inner-basic division-details">
<div class="initialmsg">
<p>A Content here</p>
</div>
<div class="a hide">
<p>A Content here</p>
</div>
<div class="b hide">
<p>B Content here</p>
</div>
</div>
</div>
There are some great answers here, but I think I'll probably go with The fourth bird's because it's the simplest. Thanks everybody!
If you are interested in a non-JS solution, you can use sibling input elements to perform a button toggle effect. Simply match the for attributes with the id attributes.
form {
display: flex;
flex-wrap: wrap;
}
input {
display: none;
}
input:checked + label {
background-color: #eee;
}
label {
cursor: pointer;
padding: 12px;
display: inline-block;
}
.container {
display: none;
background-color: #eee;
order: 1;
padding: 12px;
width: 100%;
}
input:checked + label + .container {
display: block;
}
<form>
<input id="a" type="radio" name="container" checked="checked">
<label for="a">button a</label>
<div class="container">content a</div>
<input id="b" type="radio" name="container">
<label for="b">button b</label>
<div class="container">content b</div>
</form>

How to include a input in a label in a querySelector() in javascript?

I am trying to construct a personality quiz for my school project. Everything was working fine until I decided that I want the inputs for the radio buttons to be just pictures. The problem is that I am not sure how to save the selected choice and its value, in order to calculate the result.
This is my HTML code:
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<input type="radio" name="colour" class="a" value="-1" />
<label for="p">
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
This is my CSS:
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
And this is my Javascript:
function submitSimpleQuiz() {
"use strict";
var colour = praseInt(document.querySelector('input[name = "colour"]:checked').value);
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
} else {
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function () {
$(this).addClass('selected').siblings().removeClass('selected');
});
This is just one question and answer but essentially all the answers should add up to an outcome which will display a personality description. I don't know why the button for submitting doesn't work anymore.
I would greatly appreciate the help.
I am only new to coding, but I tried including the label into the javascript and also changing the layout of the HTML so that the input is included in the label tag.
As I am sure you won't stop with only 1 question, here is a working snippet in which you can add more questions easily:
function submitSimpleQuiz() {
"use strict";
var total = 0;
var answer = ""; // Added, just because… (see below)
// Easy selection, now! That counts only "selected" inputs!
var inputs = document.querySelectorAll("#simplequiz .selected input");
for (var i = 0; i < inputs.length; i++) {
total += parseInt(inputs[i].value);
}
if (total < 0) {
answer = "Goth";
} else {
answer = "Minimalistic";
}
// Moved outside of the if to only have these instructions one time
document.getElementById("simplequiz").style.display = "none";
document.getElementById("answer").innerHTML = answer;
}
// Your other code, I haven't touched it. Promise.
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
.input_hidden {
position: absolute;
left: -9999px;
}
.selected {
background-color: #ccc;
}
#simplequiz label {
display: inline-block;
cursor: pointer;
}
#simplequiz label:hover {
background-color: #efefef;
}
#simplequiz label img {
padding: 3px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="simplequiz">
<h3>What's your favourite colour palette?</h3>
<p>
<!-- Modified order -->
<label for="p">
<input type="radio" name="colour" class="a" value="-1" />
<img src="images/2.jpg" alt="Gothic colour palette" style="width: 200px">
</label>
<!-- Added another one below -->
<label for="p">
<input type="radio" name="colour" class="a" value="1" />
<img src="images/2.jpg" alt="Minimal colour palette" style="width: 200px">
</label>
</p>
<button type="submit" value="submit" onClick="submitSimpleQuiz()">Submit</button>
</div>
<!-- Added "answer" -->
<div id="answer"></div>
Anyway, I've got a few remarks, here:
⋅ Your function submitSimpleQuiz is in JavaScript only, whereas your other code is in jQuery. You should choose what you want to use!
⋅ I moved the inputs in your labels to make it easier to select them.
⋅ Why are you using inputs if you're hiding them, and can't/don't check them?!…
Hope it helps.
You need to remove line :
$('#simplequiz input:radio').addClass('input_hidden');
Or you need to modify the line:
var colour = parseInt(document.querySelector('input[name = "colour"]:checked').value);
Because if you uncheck radiobutton you can't get the value. And You have to use parseInt not praseInt. it's an error.
First off all you need to import Jquery for using Jquery function $.
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
Second it is parseInt not praseInt.
Third:
use this piece of code instead of yours:
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
Fourth:
for your script to work correctly your javasScript should be -
<script type="text/javascript">
function submitSimpleQuiz(){
"use strict";
var colour = parseInt(document.querySelector("div#simplequiz input[name = 'colour']").value);
if (document.querySelector("div#simplequiz input[name = 'colour']").checked) {
colour = 0;
}
var total = colour;
if (total < 0) {
document.getElementById("answer").innerHTML = "Goth";
document.getElementById("simplequiz").style.display = "none";
}
else
{
document.getElementById("answer").innerHTML = "Minimalistic";
document.getElementById("simplequiz").style.display = "none";
}
}
$('#simplequiz input:radio').addClass('input_hidden');
$('#simplequiz label').click(function() {
$(this).addClass('selected').siblings().removeClass('selected');
});
</script>

Hide a div onclick through javascript

I have done for showing a div on click i want to remove on another click. I want the div to be removed on another click.
Here is the HTML code
<div id="welcomeDiv" style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />
Javascript
function showDiv() {
document.getElementById('welcomeDiv').style.display = "block";
}
You have to check the visibility of the div and do a toggle based on that.
function showDiv() {
if( document.getElementById('welcomeDiv').style.display == "none") {
document.getElementById('welcomeDiv').style.display = "block";
}
else {
document.getElementById('welcomeDiv').style.display = "none"
}
}
function showDiv() {
var element = document.getElementById('welcomeDiv');
if(!element.classList.contains('show')){
element.classList.add('show');
} else {
element.classList.remove('show');
}
}
.show {
display: block !important;
}
<div id="welcomeDiv" style="display:none;" class="answer_list" > WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv()" />
Get rid of the inline styling and use a class to toggle the display type. This is cleaner and you can easily reuse it for other elements.
function showDiv(element) {
document.querySelector(element).classList.toggle("invisible");
}
.invisible {
display: none;
}
<div id="welcomeDiv" class="answer_list invisible"> WELCOME</div>
<input type="button" name="answer" value="Show Div" onclick="showDiv('#welcomeDiv')" />
Check for the current visibility of the DIV and let the javascript function do accordingly.
function showDiv() {
if( document.getElementById('welcomeDiv').style.display == "none") {
//If it is not visible, make it visible
document.getElementById('welcomeDiv').style.display = "block";
}
else {
//Else, make it invisible.
document.getElementById('welcomeDiv').style.display = "none"
}
}

How to unhighlight button after other button is clicked (Web CSS Bootstrap)

I have a signup page with two buttons. When one button is clicked, the corresponding container displays. When a button is clicked the bg color changes and sticks, even after I select the other button. Then, if I select the button again it goes back to its unselected/inactive color.
I want the clicked button to maintain its active color, but only if the other button is not clicked. If the other button is clicked, I want the first button to go back to its original bg color.
Here is the js:
<script type = "text/javascript">
function displayForm(c) {
if (c.value == "1") {
document.getElementById("container1").style.display = 'inline';
document.getElementById("container2").style.display = 'none';
} else if (c.value == "2") {
document.getElementById("container1").style.display = 'none';
document.getElementById("container2").style.display = 'inline';
} else {}
}
</script>
And here are the buttons (sorry for formatting issues):
<!--SELECTION BUTTONS-->
<form>
<div class="control-group">
<label class="control-label">Are you a:</label>
<div class="controls">
<p><div id="account-type" name="account-type" class="btn-group selection-buttons" data-toggle="buttons-radio">
<button value="1" type="button" name="formselector" onClick="displayForm(this)" id="button1" class="btn btn-info">
Buttons1</button>
<button value="2" type="button" name="formselector" onClick="displayForm(this)" id="button2" class="btn btn-info">Button2</button>
</div></p>
</div>
</div>
</form>
Here is the CSS (using Bootstrap):
/* SWITCH BUTTONS */
.selection-buttons button{
width: 140px;
height: 60px;
color: #FFF;
background-color: #FFB10D;
border-color: #fff; /* e59f0b */
}
.selection-buttons .btn-info:hover, .btn-info:focus, .btn-info:active, .btn-info.active, .open .dropdown-toggle.btn-info {
color: #FFF;
background-color: #00CC66;
border-color: #fff; /* 00b75b */
}
Thank you!!
A pretty simple potential solution. In your JS just add the following lines:
function displayForm(c) {
for (var i = 1; i <= number_of_buttons; i++) {
if (document.getElementById("button"+i) {
document.getElementById("button"+i).className = "active";
} else {
document.getElementById("button"+i).className = "inactive";
}
}
}
Then just use your CSS file to set the formatting you want for the active and inactive classes. If you don't have 1000+ buttons, this will be efficient enough for your needs.

Categories