A toggle function for different buttons - javascript

I'd like to make two different buttons in vanilla JavaScript that, when clicked one after the other, display a different text message.
Any advice in reorganising the code below? Thanks.
I could find a toggle function for one button but not for different buttons.
index.html
<button onclick="revealMessageUk()"><li><img class="flag-pictures" src="images/uk.svg" id="1"/></li></button>
<button onclick="revealMessageSpain()"><li><img class="flag-pictures" src="images/spain.svg" id="3"/></li></button>
<p id="hiddenMessageUk" style="display:none">Hello!</p>
<p id="hiddenMessageSpain" style="display:none">¡Hola!</p>
index.js
function revealMessageUk() {
document.getElementById('hiddenMessageUk').style.display = 'block';
}
function revealMessageSpain() {
document.getElementById('hiddenMessageSpain').style.display = 'block';
}
I'd like to not only display like hereafter but have a sort of a toggle function (hide/show or add/remove feature) for the two foreign languages below.

try
function revealMessage(msg) {
hiddenMessage.style.display='block';
hiddenMessage.innerText=msg;
}
<button onclick="revealMessage('Hello!')"><li><img class="flag-pictures" src="images/uk.svg" id="1" alt='UK'/></li></button>
<button onclick="revealMessage('¡Hola!')"><li><img class="flag-pictures" src="images/spain.svg" id="3" alt='ES'/></li></button>
<p id="hiddenMessage" style="display:none"></p>

Here is a way to toggle, but also keep it flexible when more locales will be added. You keep a sort of a selectedLocaleId "state" and change it when one of the buttons is clicked with the corresponding locale id.
let selectedLocaleId;
function selectLocale(newSelectedLocaleId) {
// If there is a selected locale id, un-select it
if (selectedLocaleId) {
document.getElementById(selectedLocaleId).style.display = 'none';
}
// set the new selected locale id
selectedLocaleId = newSelectedLocaleId;
document.getElementById(selectedLocaleId).style.display = 'block';
}
<button onclick="selectLocale('hiddenMessageUk')"><li><img class="flag-pictures" src="images/uk.svg" id="1"/></li></button>
<button onclick="selectLocale('hiddenMessageSpain')"><li><img class="flag-pictures" src="images/spain.svg" id="3"/></li></button>
<p id="hiddenMessageUk" style="display:none">Hello!</p>
<p id="hiddenMessageSpain" style="display:none">¡Hola!</p>
Hope this helps :)
Cheers

Related

NWJS JS script not functioning right

Im using JS to make divs display as block or none onclick of certain inputs. When i only have it working for one input the scripts work find, but as soon as i impliment the code for the second input it glitches out and both buttons open up the div thats only supposed to work for the second button.
Some of my code:
<span name="FaviconSPAN" id="FaviconSPAN" class="FaviconSPAN" OnClick="showOrHide()">
<img src="ASSETS/IMAGES/FAVICON1.png" alt="FAVICON" name="FaviconPNG" id="FaviconPNG" class="FaviconPNG" />
</span>
<div name="SoftMenuWrapper1" id="SoftMenuWrapper1" class="SoftMenuWrapper1">
<input type="button" value="Favorites" name="SoftMenuInput1" id="SoftMenuInput1" class="SoftMenuInput1" ONCLICK="ShowAndHide()" />
<div name="SoftMenuContent1" id="SoftMenuContent1" class="SoftMenuContent1">
Link 1
Link 1
Link 1
</div>
</div>
<script type="text/javascript">
var faqPage = document.getElementById('SoftMenuContent1');
function showDiv() {
faqPage.style.display = "block";
}
function closeDiv() {
faqPage.style.display = "none";
}
function showOrHide() {
if (faqPage.style.display === "block") {
closeDiv()
}
else {
showDiv()
}
}
</script>
<SCRIPT>
function ShowAndHide() {
var x = document.getElementById('SectionName');
if (x.style.display == 'none') {
x.style.display = 'block';
} else {
x.style.display = 'none';
}
}
</SCRIPT>
First off the markup looks kinda messy. You don't need to add an ID, name, and class to everything. Only add those things if you need them.
name is rarely used, it's a way to connect to HTML elements. Like connected radio dials. You probably don't need this at all in this code.
class this should only be used if you need to add a specific CSS classname to adjust the styles. If you are not doing that, don't include it.
id should be assigned to a unique value that only occurs once on the page. it can be used to auto-scroll to that position of the page if the url contains #whatever and that matches an element with id="whatever". Though it is more commonly used just to target a specific element in your JavaScript. If you aren't doing either of those things, don't add it.
Another problem you have is order of execution. You can either define your JS first (<script> at the top) and then reference the functions with onclick in the HTML, or (more commonly), define your HTML first with ID's, then have your <script> at the bottom targeting the IDs (document.getElementById('asdf')).
Here is a cleaner version of your code.
<span id="faviconContainer">
<img src="assets/images/favicon1.png" alt="Image of an icon" />
</span>
<div>
<input type="button" value="Favorites" id="softMenuInput" />
<div id="faqPage">
Link 1
Link 2
Link 3
</div>
</div>
<script type="text/javascript">
/**
* Takes in an ID to find an element on the page, then shows/hides it.
*
* #param {string} id The element's ID
*/
function toggle (id) {
var el = document.getElementById(id);
if (el.style.display === 'block') {
el.style.display = 'none';
} else {
el.style.display = 'block';
}
}
var faviconContainer = document.getElementById('faviconContainer');
var softMenuInput = document.getElementById('softMenuInput');
faviconContainer.addEventListener('click', function () {
toggle('faqPage');
});
softMenuInput.addEventListener('click', function () {
toggle('sectionName');
});
</script>
This question isn't related to NW.js at all. It's just basic HTML and JavaScript.
I recommend you follow these resources to improve your skills. You can also rely on the world's largest programming community (HTML/JS) to ask these questions. Then when you have NW.js specific things, you can ask those here.
https://marksheet.io - HTML/CSS/Sass
https://freeCodeCamp.org - JavaScript

Show/Hide onClick button not working

Hey guys I have searched for many answers and none of them seem to be working so I am going to put my code here and hopefully you can help me figure this out.
I am going to have two buttons. The first button (show_Chappie) is going to show the hidden contents and another button (hide_Chappie) and hides it self when clicked.
The second button (hide_chappie) is going to hide the contents and bring back the first button (show_chappie). The hide_chappie button itself would also be hidden.
The information div is already hidden from the start. I did this on the CSS using the display:none;
Here's my HTML code so far:
<button class ="show_chappie" onclick="showInfo()">Show More</button>
<div class="info">Info here.</div>
<button class ="hide_chappie" onclick="hideInfo()">Show Less</button>
Here's my JavaScript code so far:
function showInfo(){
document.getElementById('chappie_info').style.display = "inline-block";
document.getElementById('show_chappie').style.display = "none";
document.getElementById('hide_chappie').style.display = "inline-block";
}
I haven't written the code for the hide_chappie button because I wanted to see this working first.
So where have I gone wrong here? Thanks for the help in advance.
You are trying to get the elements by id while they have a class, you should change the elements class to id like this:
<button id="show_chappie" onclick="showInfo()">Show More</button>
<div id="info">Info here.</div>
<button id="hide_chappie" onclick="hideInfo()">Show Less</button>
you should change your code to:
<button id ="show_chappie" onclick="showInfo()" >Show More</button>
<div class="info">Info here.</div>
<button id= "hide_chappie" onclick="showInfo()">Show Less</button>
if you want to use class here,you should change your Javascript Code to
function showInfo(){
document.getElementByClass('chappie_info')[0].style.display = "inline-block";
document.getElementByClass('show_chappie')[0].style.display = "none";
document.getElementByClass('hide_chappie')[0].style.display = "inline-block";
}
because function getElementsByClass returns a collection,so you should add [] to find out the result you want!
It's kind of annoying to turn all id's into classes, you can use:
function showInfo(){
document.getElementsByClassName('chappie_info').style.display = "inline-block";
document.getElementsByClassName('show_chappie').style.display = "none";
document.getElementsByClassName('hide_chappie').style.display = "inline-block";
}
This is supported by practically every browser these days so I wouldn't worry about that. If that is still an issue an you need to support ancient browsers, use this:
document.getElementsByClassName = function (a) {
var b = document.getElementsByTagName('*'), i, c=[];
for (i = 0; i < b.length; i += 1) { b[i].getAttribute('class')===a&&c.push(b[i]); }
return c;
};

JS expand onClick multiple events

Please check this page first : Solarking - About Us
Check first 2 boxes which has a READ MORE button. On clicking them, they expand a paragraph.
Now I want it to be like when I click on it, it should expand the text and change the button value to "CLOSE" from "READ MORE". And on again clicking on "CLOSE", it should change value to "READ MORE".
I searched for long time to see how to fire multiple events on onClick, but I saw that some said to use a ; in them, some said make a new function and put 2 functions in it.
Now I tried to make a new function with 2 functions inside it (one to expand the paragraph, other to change value of button, but I failed. (I am new to JS).
Help please. Thank you in advance!
Code I have on the page :
button code:
<p style="text-align: right;"><input id="button12" style="background-color: #eca200; color: #ffffff;" onclick="return toggleMe('para1')" type="button" value="Read more" /></p>
Script :
<script type="text/javascript">
function toggleMe(a){
var e=document.getElementById(a);
if(!e)return true;
if(e.style.display=="none"){
e.style.display="block"
}
else{
e.style.display="none"
}
return true;
}
</script>
I think the easiest way to do this would be to set a boolean variable. In other words, let's say that it starts off with the dclaration at the beginning of the page.
var hasbeenclicked = false;
Then, after the first click
hasbeenclicked = true;
After a second click
hasbeenclicked = false;
When the function is called, it checks the variable and operates accordingly. The following is not real JS....
if hasbeenclicked = true {
do some stuff;
}
else {
do some other stuff;
}
That is a simple way to accomplish what you are trying to do.
Additional info:
Use two DIV tags with separate ID's. One for the paragraph and one for the "label". Use getelementbyID to alter each one appropriately.
I noticed you are using jQuery.
You could use a toggle method.
Alter the html link. Add a class of expander and use the data attribute to identify the paragraph id
<p style="text-align: right;">
<input id="button12" data-toggle="para1" class="expander" style="background-color: #eca200; color: #ffffff;" type="button" value="Read more" />
</p>
The JS
$(".expander").click(function() {
var self = $(this);
$("#" + self.data('toggle')).slideToggle(500, function () {
if ($("#" + self.data('toggle')).is(':visible')) { // paragraph is open
self.val("Close");
} else { // paragraph is closed
self.val("Read More");
}
});
});

Switch class and disable button

Is it possible to also switch the class to a loading graphic and disable the button when onClick is called and before the location.href is launched? There is a delay and I'm hoping to avoid double clicks. Can someone show me a sample of this?
<button type="button" class="MoreTides" onclick="location.href='http://www.domain.com/tides/parser_iphone.php?stats=$xml->stationid'">View Graph - Change Dates</button>
Something like this might be a start:
<script>
function loadPage(input) {
input.disabled = true;
input.className = "loadingButton"; // define how this should look in CSS
location.href='http://www.domain.com/tides/parser_iphone.php?stats=$xml->stationid';
}
</script>
<button type="button" class="MoreTides" onclick="loadPage(this)">View Graph - Change Dates</button>

Replacing Checkbox with image and update onClick (possibly jQuery?)

Is there a way that I can have an image replace a checkbox, and when someone clicks on it, it selects it, and changes the image to another image like a "checked" image?
So essentially:
[heart-icon] Health and Fitness
user clicks on it
[check-icon] Health and Fitness
and now that area is selected
There are definitely scripts/plugins available to do this. I've not used any of them so I can't recommend one specifically, but here's an example:
http://www.itsalif.info/content/ezmark-jquery-checkbox-radiobutton-plugin
I would try this plugin: SimpleImageCheck
http://www.jkdesign.org/imagecheck/
Code to customize the checkbox looks simple:
$('#checkbox').simpleImageCheck({
image: 'unchecked.png',
imageChecked: 'check.png'
afterCheck: function(isChecked) {
if (isChecked) {
// do something
}
}
});
No need of plugins nor JQuery:
<span onclick="changeCheck(this)">
<img src="http://www.clker.com/cliparts/e/q/p/N/s/G/checkbox-unchecked-md.png">
<img src="http://www.clker.com/cliparts/4/h/F/B/m/4/nxt-checkbox-checked-ok-md.png">
<input type="checkbox" name="chk">
</span>
<script>
function changeCheck(target)
{
chk = target.lastElementChild;
chk.checked = !chk.checked;
target.children[+ chk.checked].style.display = '';
target.children[1 - (+ chk.checked)].style.display = 'none';
}
function initCheck()
{
chk = document.getElementsByName('chk')[0];
chk.style.display = 'none';
chk.parentNode.children[1 - (+ chk.checked)].style.display = 'none';
}
initCheck();
</script>

Categories