javascript change <p> display with buttons - javascript

I want to change the paragraphs visibility to none or hidden dynamicly using javascript.I have 4 paragraphs and I want only one to be displayed.If a user clicks right button the next parargraph should be displayed instead of the previous one.If left button, then another way.But my event handlers don't seem to respond inside the paragrap_switch function.Please help me with that
HTML
<head>
<style>
p{
border:1px solid black;
width:20%;
display:none;
}
input{
width:40px;
}
</style>
</head>
<body>
<p class="paragraph">TEXT 1</p>
<p class="paragraph">TEXT 2</p>
<p class="paragraph">TEXT 3</p>
<p class="paragraph">TEXT 4</p>
<input type = "button" value = "left" class = "button"/>
<input type = "button" value = "right" class = "button"/>
And Javascript
function paragraph_switch (){
var paragraphs = document.getElementsByClassName('paragraph');
var buttons = document.getElementsByClassName('button');
for(var i = 0;i < paragraphs.length; i++){
if(i >= 0){
if(buttons[0].onclick = function(){
paragraphs[i].style.display = "none";
paragraphs[i+1].style.display = "block";
i++;
}
else if(buttons[1].onclick = function(){
paragraphs[i].style.display = "none";
paragraphs[i-1].style.display = "block";
i--;
}
}
}
}

I am not sure what your code is doing. You are assigning eventhandler inside the if condition.
I have implemented your requirement using jQuery. Here is the jsfiddle.
http://jsfiddle.net/DyZf2/
Here is the js code.
$("p:first").show();
$("#left").click(function(){
$("p:visible").hide().prev().show();
});
$("#right").click(function(){
$("p:visible").hide().next().show();
});
You may have to modify the code to make sure that next/previous paragraph exists before hiding the current one.

Related

javascript expand/collapse text - collapse on default

I'm very inexperienced in javascript but have managed (with the help of google) to put together the following expandable/collapsible link
<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>
<p>
<input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" />
</p>
<p id="para1">
<strong><em>text text text text</em></strong>
</p>
The only problem with it is that it is expanded by default and I wanted it collapsed by default. Can anyone help with this? Thank you!
Also, if anyone knows how to get +/- signs next to the link that change depending on whether it is expanded or collapsed, that would be great.
<script type="text/javascript">
function toggleMe(a) {
var e = document.getElementById(a);
var toggleIcon = document.getElementById('toggle-icon');
if(!e) return true;
if(e.style.display == "none") {
e.style.display = "block";
toggleIcon.innerHTML = '-';
}
else {
e.style.display = "none";
toggleIcon.innerHTML = '+';
}
return true;
}
</script>
<p>
<input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" />
<span id="toggle-icon">+</span>
</p>
<p id="para1" style="display: none;">
<strong><em>text text text text</em></strong>
</p>
You can try putting in style statement the display option like below:
<p id="para1" style="display:none"><strong><em>text text text text</em></strong></p>
That can default collapse when you open your html, hope it help you...
Options 1:
Add this to your css to hide it by default:
#para1 {
display: none;
}
Options 2:
Move your script down, and call it initially toggleMe('para1'); so you will hide it first.
<p>
<input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" />
</p>
<p id="para1">
<strong><em>text text text text</em></strong>
</p>
<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;
}
toggleMe('para1');
</script>
Daniel has the correct answer to your question. This is a bit more than you asked for, but I think you will have a better time if you manipulate classes instead of element styles properties. Just makes it a bit more flexible.
In the example below I wrapped your code in a common element and then changed that element's class to achieve your desired effect. That let me easily add in your plus and minus too.
It's a little raw but you can see where this can take you. Hope it helps.
https://jsfiddle.net/6xoe1b94/
function toggleMe(a) {
var e = document.getElementById('wrapper');
if(! e.classList.contains('active')) {
e.classList.add('active');
}
else {
e.classList.remove('active');
}
}
#para1{
display:none;
}
.active #para1{
display:block;
}
#plus{
display:inline-block;
}
#minus{
display:none;
}
.active #plus{
display:none;
}
.active #minus{
display:inline-block;
}
<div id='wrapper'>
<p>
<input onclick="return toggleMe('para1')" style="font-size:18px; color:#008080;" type="text" value="LINK TO EXPAND" /><span id='plus'>+</span><span id='minus'>-</span>
</p>
<p id="para1">
<strong><em>text text text text</em></strong>
</p>
</div>
I added a solution that removes the javascript and css from your html. I also changed your expand/collapse element to a div instead of input. I've added a span element within the div that changes it's text content (either + or -) based on whether #para1 is displayed or not. Also, in css I added display: none; to #para1 (this initially hides the element), cursor: pointer; (shows it is clickable when the user hovers over it) user-select: none; (stop div from highlighting when user clicks on it).
// store elements
var expandEl = document.getElementById("expand");
var plusMinusEl = document.getElementById("plusMinus");
var para1El = document.getElementById("para1");
// toggle function: pass element as argument
function toggleMe(el) {
// check if element is hidden
if(el.offsetParent === null) {
plusMinusEl.textContent = "-";
el.style.display = "block"
}
else {
plusMinusEl.textContent = "+";
el.style.display = "none"
}
}
// click function for expand div
expandEl.addEventListener("click", function() {toggleMe(para1El)});
#expand {
font-size:18px;
color:#008080;
cursor: pointer;
user-select: none; /* stop div from highlighting */
}
#para1 {
display: none;
}
<div id="expand">
LINK TO EXPAND <span id="plusMinus">+</span>
</div>
<p id="para1"><strong><em>text text text text</em></strong></p>

Apply a JavaScript function to all Array elements except the ith element

In one of my projects I made 3 galleries, I would like to put both of them on the same page in the same position, not at the same time, however. For this to be possible, I chose to create 3 buttons. When I click on the first button for example, the first gallery should appear (both galleries are initially on display:none), then when I click on the second button, the second one should appear and the one shown before should disappear, and so for each of the galleries. I made a simplified copy of the page to make the thinking easier.
In general, my problem is that I don't quite know how to apply a function to all the elements in an Array except for one element.
Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Galleries</title>
<link rel="stylesheet" type="text/css" href="gs.css">
<style type="text/css">
body{
background-color:royalblue;
}
header{
text-align: center;
}
article{
width:95%;
margin:auto 2.5% auto 2.5%;
height:850px;
background-color:tomato;
display:none;
}
</style>
</head>
<body>
<header>
<button>Third Gallery</button>
<button>Second Gallery</button>
<button>Third Gallery</button>
</header>
<section>
<article>
<h1>This is the first gallery</h1>
</article>
<article>
<h1>This is the second gallery</h1>
</article>
<article>
<h1>This is the third gallery</h1>
</article>
</section>
<script type="text/javascript">
var button=document.getElementsByTagName('button');
var gallery=document.getElementsByTagName('article');
for(var i=0; i<button.length; i++){
(function(index){
button[index].onclick=function(){
gallery[index].style.display="block";
}
}(i));
}
</script>
</body>
</html>
You could iterate over all the elements and compare the index of the button with the index of the current gallery item:
[].forEach.call(gallery, function (el, i) {
el.style.display = i === index ? 'block': 'none';
});
or:
for (var i = 0; i < gallery.length; i++) {
gallery[i].style.display = i === index ? 'block': 'none';
}
This will loop over all the elements and set the display of each element to none except for the on with an index that corresponds to the clicked button.
Example Here
var button = document.getElementsByTagName('button');
var gallery = document.getElementsByTagName('article');
for (var i = 0; i < button.length; i++) {
(function(index) {
button[index].onclick = function() {
[].forEach.call(gallery, function (el, i) {
el.style.display = i === index ? 'block': 'none';
});
}
}(i));
}
What you have done is almost right... Loop through the whole thing and when the particular element comes, do not do that, but I don't understand what's the use of closure here:
var button=document.getElementsByTagName('button');
var gallery=document.getElementsByTagName('article');
for(var i=0; i<button.length; i++){
if (i != 2) // Make sure `i` is not equal to 2.
(function(index){
button[index].onclick=function(){
gallery[index].style.display="block";
}
}(i));
}

managing several show/hide divs

I have some scripts here that show and hide divs when click. Now what I need is to just only display one div at a time. I have a code that controls them all but its not working I don't know about much of javascript.
This is the first example of show/hide function that can be done simultaneously without hiding the other divs.
FIDDLE HERE
HTML:
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" style="display:none;">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" style="display:none;">
<p>Content goes here.</p>
</div>
SCRIPT:
function HideContent(d) {
document.getElementById(d).style.display = "none";
}
function ShowContent(d) {
document.getElementById(d).style.display = "block";
}
function ReverseDisplay(d) {
if (document.getElementById(d).style.display == "none") {
document.getElementById(d).style.display = "block";
} else {
document.getElementById(d).style.display = "none";
}
}
function HideAllShowOne(d) {
// Between the quotation marks, list the id values of each div.
var IDvaluesOfEachDiv = "idone idtwo uniquename1 uniquename";
//-------------------------------------------------------------
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/[,\s"']/g," ");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/^\s*/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/\s*$/,"");
IDvaluesOfEachDiv = IDvaluesOfEachDiv.replace(/ +/g," ");
var IDlist = IDvaluesOfEachDiv.split(" ");
for(var i=0; i<IDlist.length; i++) { HideContent(IDlist[i]); }
ShowContent(d);
}
The other fiddle I created would do what I need but the script seems not to be working. Fiddle here
Found the solution on my code thanks to #Abhas Tandon
Fiddle here the extra id's inside the IDvaluesOfEachDiv seems to be making some error with the codes.
If you are happy with IE10+ support then
function ReverseDisplay(d) {
var els = document.querySelectorAll('.toggle.active:not(#' + d + ')');
for (var i = 0; i < els.length; i++) {
els[i].classList.remove('active');
}
document.getElementById(d).classList.toggle('active')
}
.toggle {
display: none;
}
.toggle.active {
display: block;
}
<a href="javascript:ReverseDisplay('uniquename')">
Click to show/hide.
</a>
<div id="uniquename" class="toggle">
<p>Content goes here.</p>
</div>
<a href="javascript:ReverseDisplay('uniquename1')">
Click to show/hide.
</a>
<div id="uniquename1" class="toggle">
<p>Content goes here.</p>
</div>
I would suggest to use jQuery which is far easier.
Include thiswithin
<head>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
HTML
<div id="id_one">Item 1</div>
<div id="content_one">
content goes here
</div>
<div id="id_two">Item 1</div>
<div id="content_two">
content goes here
</div>
Script:
$(function()
{
$("#content_one").hide();
$("#content_two").hide();
});
$("#id_one").on("click",function()
{
$("#content_one").slideDown("fast");
});
$("#id_two").on("click",function()
{
$("#content_two").slideDown("fast");
});
If you have a "Button" for every DIV inside your HTML - you can go by element index
var btn = document.querySelectorAll(".btn");
var div = document.querySelectorAll(".ele");
function toggleDivs() {
for(var i=0; i<btn.length; i++) {
var us = i===[].slice.call(btn).indexOf(this);
btn[i].tog = us ? this.tog^=1 : 0;
div[i].style.display = ["none","block"][us?[this.tog]:0];
}
}
for(var i=0; i<btn.length; i++) btn[i].addEventListener("click", toggleDivs);
.btn{/* Anchors Buttons */ display:block; cursor:pointer; color:#00f;}
.ele{/* Hidden Divs */ display:none;}
<a class="btn"> 1Click to show/hide.</a>
<div class="ele"><p>1Content goes here.</p></div>
<hr>
<a class="btn">2Click to show/hide.</a>
<div class="ele"><p>2Content goes here.</p></div>
<hr>

How do I change an ID to a Class in JavaScript

I'm unfamiliar with JavaScript and I've been trying to figure this out for days now and I just can't seem to get it to work.
I have this JSFiddle
http://jsfiddle.net/xslibx/nG4Zz/
HTML
<h4 id="tweet" >Some text here</h4>
<h4 id="tweet" >Some more text here</h4>
CSS
#tweet, #tweet_js { border:1px solid red; width:70px; padding:.5em; }
#tweet_js { overflow:hidden; white-space:nowrap; }
.hiding { text-overflow:ellipsis; }
JavaScript
var tweet = document.getElementById('tweet');
tweet.id = 'tweet_js';
tweet.className = 'hiding';
var slide_timer,
max = tweet.scrollWidth,
slide = function () {
tweet.scrollLeft += 1;
if (tweet.scrollLeft < max) {
slide_timer = setTimeout(slide, 40);
}
};
tweet.onmouseover = tweet.onmouseout = function (e) {
e = e || window.event;
e = e.type === 'mouseover';
clearTimeout(slide_timer);
tweet.className = e ? '' : 'hiding';
if (e) {
slide();
} else {
tweet.scrollLeft = 0;
}
};
It is a scolling text effect for when the text is larger than the container the overflow is hidden. It is revieled when the mouse hovers over the text
this effect works for the first container but does not work for the second.
I have a feeling it's because it uses ID (#tweet, #tweet_js) instead of a CLASS (.tweet, .tweet_js). How would I change the JavaScript code so it works with classes instead of IDs
<h4 class="tweet" >Some text here</h4>
<h4 class="tweet" >Some more text here</h4>
Thank you in advance
You're right about the duplicate IDs causing problems. An ID is supposed to be unique. Once you add more that one element with the same ID to a document, all bets are off.
In order to change your code, use class="whatever" in your markup, and access an array of matching elements using document.getElementsByClassName("whatever").
HTML:
<h4 class="tweet" >Some text here</h4>
<h4 class="tweet" >Some more text here</h4>
JS:
var tweets = document.getElementsByClassName('tweet');
// Apply the hidden class to all tweets
for(var i = 0; i < tweets.length; i++) {
tweets[i].classlist.add('hidden');
}
...

Javascript check if event handler has been clicked

I want to display paragraphs with the help of js, and I want for every time that user clicks button "right" to display a paragraph but instead all of the paragraphs are being showed. How can I check if a user has clicked a button, so that I can display only ONE next paragraph when the button was clicked.
Thanx in advance.
<style type="text/css">
p {
border:1px solid black;
width:100px;
height:30px;
display:none;
}
</style>
<p>some text1</p>
<p>some text2</p>
<p>some text3</p>
<p>some text4</p>
<p>some text5</p>
<input type="button" value = "left" />
<input type="button" value = "right"
onclick = "
var p = document.getElementsByTagName('p');
for(var i = 0; i <p.length; i++){
show_paragraphs(i);}
"
id = "right"/>
You need to Itrate over each para and check if the previous para is displayed;if displayed set as display none for the previous and for display block as for current one and return.
here is the sample code
<html>
<style type="text/css">
p {
border:1px solid black;
width:100px;
height:30px;
display:none;
}
</style>
<p style="display:block">some text1</p>
<p>some text2</p>
<p>some text3</p>
<p>some text4</p>
<p>some text5</p>
<input type="button" value = "left" />
<input type="button" value = "right"
onclick = "navigate()"
id = "right"/>
<script>
function navigate(){
var p = document.getElementsByTagName('p');
for(var i = 1; i <p.length; i++){
if( p[i-1].style.display == 'block')
{
p[i].style.display = 'block' ;
p[i-1].style.display ='none';
return;
}
}
}
</script>
</html>
Check out the Content Swapper jQuery plug-in which does exactly what you're trying to do.
Or if you must do it your way, here's your code modified to work:
<!doctype html>
<html>
<head>
<style type="text/css">
p {
border:1px solid black;
width:100px;
height:30px;
display:none;
}
</style>
<script>
var i=0, paras = document.getElementsByTagName('p');
function hideAllPara() {
for(var j=0; j<paras.length; j++) {
paras[j].style.display = 'none';
}
}
</script>
</head>
<body>
<p>some text1</p>
<p>some text2</p>
<p>some text3</p>
<p>some text4</p>
<p>some text5</p>
<input type="button" value = "left" />
<input type="button" value = "right" onclick = "hideAllPara(); paras[i].style.display = 'block'; i = (i < paras.length-1) ? i+1 : 0;" id = "right"/>
</body>
</html>
You must note though, working with inline click events or JavaScript is never recommended.
Anyway, so basically each time you click the right button, first we need to hide all paragraphs, then display only the one required; to do that we need to keep track of the index/pointer and reset it once we've reached the end.
And if you wish to show a paragraph when the page load, you could do any of the following in CSS:
p:first-child {display: block;}
p:nth-child() /* specify whatever index you wish to show off all the selected paragraphs on the page */
Give a class name called "active" to the paragraph you wish to show and declare it in CSS as so; p.active {display: block;}
What about:
var left=document.getElementById("left");
var right=document.getElementById("right");
var show=function(){
var paragraphs=document.getElementsByTagName("p");
var current=0;
var len=paragraphs.length;
return function(event){
var button=event.target.id;
var direction=0;
var visi="visible";
if(button==="left"){
visi="hidden";
direction=(current>0)?-1:0;
} else {
direction=(current<len-1)?1:0;
}
paragraphs[current].style.visibility=visi;
current+=direction;
};
}();
left.addEventListener("click", show);
right.addEventListener("click", show);
jsFiddle

Categories

Resources