I am trying to toggle between a couple of texts, where the only one that shows is the one that was "turn on" most recently. For example, the default would look something like this:
Click A
Click B
If you click 'Click B', the text for that will toggle to something else, let's say "You've clicked B".
Click A
You've Clicked B
If you click 'Click A' right afterwards, then the previous text will go back to its default, ie "You've Clicked B" will revert back to 'Click B' and then 'Click A' will be turn on.
Right now, neither of them are toggling, they are just both on.
Here is what I have:
JavaScript
toggle_visibility("t1");
toggle_visibility("t2");
function toggle_visibility(id) {
function toggle(id){
var text = document.getElementById(id);
if(text.style.display == 'none'){
text.style.display = 'block';
}
else{
text.style.display = 'none';
}
}
toggle(id);
}
HTML
<div id="t1" <a href="Click A" onclick="toggle_visibility('t1');">
<h1>You've Clicked A</h1></div>
<div id="t2" <a href="Click B" onclick="toggle_visibility('t2');">
<h1>You've Clicked B</h1></div>
It's better if you assign an id to the <h1> tag like this and I have added some attributes:
<div> <a href="#" onclick="toggle_visibility('t1');">
<h1 id="t1" data-original="Click A" data-after="You've clicked A" data-toggled="0">Click A</h1></div>
<div> <a href="#" onclick="toggle_visibility('t2');">
<h1 id="t2" data-original="Click B" data-after="You've clicked B" data-toggled="0">Click B</h1></div>
For the JS, you can use this:
<script>
var isFirst = true;
function toggle_visibility(id) {
if(!isActivated(id)) {
toggle(id);
if(isFirst != true) {
if(id == "t1") {
toggle("t2");
} else if(id == "t2") {
toggle("t1");
}
}
}
isFirst = false;
}
function toggle(id) {
var text = document.getElementById(id);
if(text.getAttribute("data-toggled") == "1") {
text.setAttribute("data-toggled", "0");
text.innerHTML = text.getAttribute("data-original");
}
else {
text.innerHTML = text.getAttribute("data-after");
text.setAttribute("data-toggled", "1");
}
}
function isActivated(id) {
var element = document.getElementById(id);
if(element.getAttribute('data-toggled') == "1") {
return true;
} else {
return false;
}
}
</script>
Check your HTML first.
<div id="t1">**** <a href="Click A" onclick="toggle_visibility('t1');">
<h1>You've Clicked A</h1></div>
<div id="t2">**** <a href="Click B" onclick="toggle_visibility('t2');">
<h1>You've Clicked B</h1></div>
There should be a closing ">" near the place I marked ****. Again, you have not closed your anchor tag with an "</a>"
I can't be sure that I interpreted your HTML correctly (there are several errors in it), but other than that, I believe this solves the problem:
var visibleText;
function toggle_visibility(id) {
var text = document.getElementById(id).lastElementChild;
if (text.style.display === 'none') {
if (visibleText) visibleText.style.display = 'none';
visibleText = text;
text.style.display = 'block';
} else {
text.style.display = 'none';
}
}
This code keeps track of any currently toggled-on 'text' in a variable declared outside the scope of the toggle_visibility function. This allows you to easily toggle off any currently visible text and switch on the desired text.
And here's a JSFiddle.
Related
I have a link with a plus symbol (More Details[+]) ... when the user clicks the link, I want the link to change to a minus (More Details[-]), and show the content below it. I can show/hide the content, but the +/- toggle doesn't work. Note: I'm new to javascript, so please be patient with my lack of knowledge...
Note: There are a few posts about +/- toggles. I need help with the code that I wrote below.
Below is the javascript...
// Plus/Minus Toggle
function toggle_plus(id) {
var f = document.getElementById(id);
if (f.classList.contains("showplus")) {
f.removeClass("showplus");
f.addClass("showminus");
} else {
f.removeClass("showminus");
f.addClass("showplus");
}
}
// Toggle to show and hide content below the link
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
And below is the html for the content.....
<div class="teamdetail">
More Details [<span id="team4Plus" class="showplus"></span>]
</div>
<div id="team4" class="teamtxt">
Text Goes Here
</div>
And the CSS for the showplus and showminus
.showminus:before { content: '-'; }
.showplus:before { content: '+'; }
.removeClass and .addClass are jQuery functions. You need to use .classList.add and .classList.remove
// Plus/Minus Toggle
function toggle_plus(id) {
var f = document.getElementById(id);
if (f.classList.contains("showplus")) {
f.classList.remove("showplus");
f.classList.add("showminus");
} else {
f.classList.remove("showminus");
f.classList.add("showplus");
}
}
// Toggle to show and hide content below the link
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block') {
e.style.display = 'none';
} else {
e.style.display = 'block';
}
}
.showminus:before { content: '-'; }
.showplus:before { content: '+'; }
<div class="teamdetail">
More Details [<span id="team4Plus" class="showplus"></span>]
</div>
<div id="team4" class="teamtxt">
Text Goes Here
</div>
In addition to Dave's answer (I don't have enough rep to comment :/), toggle is your friend.
// Plus/Minus Toggle
function toggle_plus(id) {
var f = document.getElementById(id);
f.classList.toggle("showplus");
f.classList.toggle("showminus");
}
Will do the same.
Also, the Chrome inspector console is your friend - it would've been throwing up errors to you. https://developers.google.com/web/tools/chrome-devtools/console/
I have this piece of code which i use for language toggling:
function toggleDiv(divid) {
varon = divid + 'on';
varoff = divid + 'off';
if(document.getElementById(varon).style.display == 'block'){
document.getElementById(varon).style.display = 'none';
document.getElementById(varoff).style.display = 'block';
}
else {
document.getElementById(varoff).style.display = 'none';
document.getElementById(varon).style.display = 'block'
}
}
and HTML:
<div id="mydivon" style="display:block">some language text</div>
<div id="mydivoff" style="display:none">some other language text</div>
Language1/Language2
and i would like to make toggle button switchable, when one Language1 is selected, switch toggle text to Language2 and vice versa. Some pointers would be welcome. Thx
I've setup a Fiddle , is this the effect you wanted to achieve? As #Shilly already said in the comments, you can use textContent to change the content of your anchor tag.
I've assigned an ID to your anchor #languageSwitch so I can do following stuff in your JS
HTML
<div id="mydivon" style="display:block">
Language 1 is selected
</div>
<div id="mydivoff" style="display:none">
Language 2 is selected
</div>
<a id="languageSwitch" href="#" onmousedown="toggleDiv('mydiv');">
Switch to Language2
</a>
JS
function toggleDiv(divid) {
varon = divid + 'on';
varoff = divid + 'off';
// Assign the switch anchor to a variable
var switcher = document.getElementById('languageSwitch');
if (document.getElementById(varon).style.display == 'block') {
document.getElementById(varon).style.display = 'none';
document.getElementById(varoff).style.display = 'block';
//Change the text to language1 (language 2 is active)
switcher.textContent = "Switch to Language1";
} else {
document.getElementById(varoff).style.display = 'none';
document.getElementById(varon).style.display = 'block'
//Change the text to language2 (language 1 is active)
switcher.textContent = "Switch to Language2";
}
}
As described by the OP in the comments:
Currently you're displaying an element on wether it's selected but the toggle itself isn't changing language.
Now what you can do is when you mousedown and execute toggleDiv(divid)
there should be a special variable to your disposal called this
this basically means "this called me" in the most simple form.
In your case this is the Language1/Language2 link
So what you could do then within your function:
function toggleDiv(divId) {
//also highly recommend you cache your variables
varon = document.getElementById(divId + 'on');
varoff = document.getElementById(divId + 'off');
if (varon.style.display == 'block') {
varon.style.display == 'none';
varoff.style.display = 'block';
this.innerHTML = varoff.innerHTML; // <- selected element value injected in bound button
} else
varon.style.display == 'block';
varoff.style.display = 'none';
this.innerHTML = varon.innerHTML; // <- selected element value injected in bound button
}
With the line this.innerHTML = varon/off.innerHTML you're saying, "the element that called me has to have the value of the block element"
The value will still default be Language1/Language2 but as soon as you change it it will update.
Hope it helps!
NOTE: UNTESTED
Step 1: Add an id to your link:
<a id="toggle-language" href="#" onmousedown="toggleDiv('mydiv');">Language1/Language2</a>
Step 2: Change your function to:
function toggleDiv(divid) {
var on = document.getElementById(divid + 'on'),
off = document.getElementById(divid + 'off'),
language = document.getElementById('toggle-language');
if (on.style.display == 'block'){
on.style.display = 'none';
off.style.display = 'block';
language.textContent = 'Language 2';
}
else {
on.style.display = 'block';
off.style.display = 'none';
language.textContent = 'Language 1';
}
}
Hello: I am basically trying to have a toggle button (javascript) that when you click it a div appears and when you click it again the div disappears...
I found some code on here which basically does that; except the div is initially outputted on the page
(http://gerardsites.com/index)
I am new to learning javascript; and so I am trying to adapt this so that when page loads the div (gman123); is not shown; and then the button just toggles it...
here is the code:
<script type="text/javascript">
function toggleMe(btn, a) {
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
e.style.display = "block";
btn.value = "MENU";
}
else {
e.style.display = "none";
btn.value = "MENU";
}
return true;
}
</script>
<input type="button" onclick="return toggleMe(this,'gman123')" value="MENU"><br>
<div id="gman123">
<br />
How about this for test text?
</div>
Can anyone help on this?
Thanks so much,
G
<html>
<body>
<script type="text/javascript">
function toggleMe(btn, a) {
var e = document.getElementById(a);
if (!e) return true;
if (e.style.display == "none") {
e.style.display = "block";
btn.value = "MENU";
}
else {
e.style.display = "none";
btn.value = "MENU";
}
return true;
}
</script>
<input type="button" onclick="return toggleMe(this,'gman123')" value="MENU">
<br>
<div id="gman123" style="display: none">
<br />
How about this for test text?
</div>
</body>
</html>
Add some CSS to hide the element initially...
Like so...
#gman123 {display:none}
your code is pretty fine. but since you wanna make this hidden on when the page load. so you have to hide it manually . Alternatively what you can do is call your function when page load is complete for that just add following code just before closing of your body Tag
<script type="text/javascript">
toggleMe(this,'gman123');
</script>
This will hide it for just one time . you can use this trick in future too.
This is my first real dive into javascript. I've been going at this for hours and haven't found a solution (though I learned a lot).
<script type="text/javascript">
function changeClass(){
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function()
{
document.getElementById("switcher").addEventListener( 'click' , changeClass );
}
</script>
Here is the HTML:
<div class="switch switch-blue" id="switcher">
<input type="radio" class="switch-input" name="resp" value="1" id="respyes" checked>
<label for="respyes" class="switch-label">YES</label>
<input type="radio" class="switch-input" name="resp" value="2" id="respno">
<label for="respno" class="switch-label">NO</label>
</div>
The default is a blue background. If they choose no I want it red, then back to blue if they click yes, all that is in the css. If I manually change the class from switch-blue to switch-red, it works. Right now it does absolutely nothing.
Thank you!
Problem here is event propagation when an internal element click event bubbleup so it causing calling your function twice which change class and then revert back so try:
function changeClass(event) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (currentClass == "switch switch-blue") {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
if (window.event != undefined) window.event.cancelBubble = true;
event.stopPropagation();
}
window.onload = function () {
document.getElementById("switcher").addEventListener('click', changeClass);
}
event.stopPropagation(); will stop this bubbling and for IE use window.event.cancelBubble = true;
Here is working JSFiddle
Edit
But this will not guarentee the change of class on radio button click as event is bind to parent div so clicking over div anywhere will trigger the event, so try to bind event on the radio-buttons:
Event on Radio click
function changeClass(clickedItem) {
var NAME = document.getElementById("switcher");
var currentClass = NAME.className;
if (clickedItem == 1) {
NAME.className = "switch switch-red";
} else {
NAME.className = "switch switch-blue";
}
}
window.onload = function () {
var yes = document.getElementById('respyes');
var no = document.getElementById('respno');
yes.onclick = function () {
changeClass(2)
};
no.onclick = function () {
changeClass(1)
};
}
function changeClass(elem){
var currentClass = elem.className, blueClass = "switch switch-blue",
redClass= "switch switch-red"
elem.className = (currentClass == blueClass) ? redClass:blueClass;
}
window.onload = function()
{
document.getElementById("switcher").onclick = function(){
changeClass(this);
};
}
JS Fiddle: http://jsfiddle.net/dYt8v/
Looks like it is working fine, when you add the css classes.
Here is a demo. I think you are missing the styles.
Add the style to your head and see if that works for you.
<style>
.switch-blue{
background:blue;
color:#fff;
}
.switch-red{
background:red;
color:#fff;
}</style>
Feel free to change the styles as you need them.
Edit
I just noticed that you have the event listeners attached to the div instead of the radio button. That will change the background when you click the div, instead of the buttons. See this updated fiddle.
The code below is a link which when clicked will open and close an initially hidden div. It works fine other than having to click the link twice in the first instance to open it. It's not a major problem but if it can be made so that the div opens on the first click that would be great.
toggleDiv.js
function toggleDiv(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false);
} else {
elem.attachEvent('on' + eventType, handler);
}
}
toggleDiv(window, 'load', function() {
var link = document.getElementById('myMagicLink'),
div = document.getElementById('foo');
toggleDiv(link, 'click', function() {
if (!link) return true;
if (div.style.display == "none") {
div.style.display = "block"
} else {
div.style.display = "none"
}
return true;
});
});
index.html
<body>
<a id="myMagicLink" href="http://www.google.com/">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
<script language="JavaScript" type="text/javascript" src="toggleDiv.js"></script>
</body>
I had the same problem for toggling the display value of an ASIDE tag. Switching from "none" to "inline" and back again would not work on the first click. Display was set to "none" in my CSS file.
In my script I changed "none" to "" (which seems to mean "default" as far as I understand). The following code works fine for me now.
var x = document.getElementsByTagName("aside")[0];
if (x.style.display == "")
{
x.style.display = "inline";
}
else
{
x.style.display = "";
}
I understood this when I saw the CSS/actual values in Firefox developer tools: "aside" is shown with CSS attributes, but an "element" is first shown with no attribute. On first click, "element" was assigned a "display" attribute set to "none".
Not sure what the trouble you are having this... this works flawlessly for me in Chrome.
I did change the url of your link to reflect back to the same document, but the div foo is hiding and reappearing as it should.
Couple of style notes: Rather than setting display = "block" it is better to say display = "" so it can return to its default value.
In addition, I also included a preventDefault function. Your use of return true would work for DOM0 style event handling, but it did not work with the attachEvent/addEventHandler code. This properly keeps the link from being followed.
<html>
<head>
<title>Test</title>
<script>
function toggleDiv(elem, eventType, handler) {
if (elem.addEventListener) {
elem.addEventListener(eventType, handler, false);
} else {
elem.attachEvent('on' + eventType, handler);
}
}
toggleDiv(window, 'load', function() {
var link = document.getElementById('myMagicLink'),
div = document.getElementById('foo');
toggleDiv(link, 'click', function(e) {
if (!link) return cancelDefaultAction(e);
if (div.style.display == "none") {
div.style.display = "block"
} else {
div.style.display = "none"
}
return cancelDefaultAction(e);
});
});
function cancelDefaultAction(e) {
var evt = e ? e:window.event;
if (evt.preventDefault) evt.preventDefault();
evt.returnValue = false;
return false;
}
</script>
<body>
<a id="myMagicLink" href="#">My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>
Sorry it seems a bit complicated for something pretty simple, unless you have a specific design in mind; but this should work equally well:
The Fiddle
<html>
<head>
<script language="JavaScript" type="text/javascript">
var toggled = false;
function toggleDiv()
{
if(toggled)
{
document.getElementById('foo').style.display = '';
toggled = false;
}
else
{
document.getElementById('foo').style.display = 'none';
toggled = true;
}
}
</script>
</head>
<body>
<a id="myMagicLink" href="http://www.google.com/" onClick='toggleDiv()'>My Magic Link</a>
<div id="foo">Opens a div</div>
<br>
End of page
<br>
</body>
</html>