show more/Less text with just HTML and JavaScript - javascript

I am needing to create a show more/less text function, but with just JavaScript and HTML.. I can't use any additional libraries such as jQuery and it can't be done with CSS. The sample code I have added displays the 'more' text, but not the 'less'.
If someone could point me in the right direction, it would be much appreciated.
I've spent the majority of the day frying my brain over this, as its clearly not the modern way to do it, however, my HTML is:
<html>
<head>
<script type="text/javascript" src="moreless.js"></script>
</head>
<body>
Lorem ipsum dolor sit amet
<p>
<p id="textarea"><!-- This is where I want to additional text--></div>
</p>
<a onclick="showtext('text')" href="javascript:void(0);">See More</a>
<p>
Here is some more text
</body>
</html>
and my JavaScript is (moreless.js):
function showtext()
{
var text="Here is some text that I want added to the HTML file";
document.getElementById("textarea").innerHTML=text;
}

My answer is similar but different, there are a few ways to achieve toggling effect. I guess it depends on your circumstance. This may not be the best way for you in the end.
The missing piece you've been looking for is to create an if statement. This allows for you to toggle your text.
More on if statements here.
JSFiddle: http://jsfiddle.net/8u2jF/
Javascript:
var status = "less";
function toggleText()
{
var text="Here is some text that I want added to the HTML file";
if (status == "less") {
document.getElementById("textArea").innerHTML=text;
document.getElementById("toggleButton").innerText = "See Less";
status = "more";
} else if (status == "more") {
document.getElementById("textArea").innerHTML = "";
document.getElementById("toggleButton").innerText = "See More";
status = "less"
}
}

With some HTML changes, you can absolutely achieve this with CSS:
Lorem ipsum dolor sit amet
<p id="textarea">
<!-- This is where I want to additional text-->
All that delicious text is in here!
</p>
<!-- the show/hide controls inside of the following
list, for ease of selecting with CSS -->
<ul class="controls">
<li class="show">Show</li>
<li class="hide">Hide</li>
</ul>
<p>Here is some more text</p>
Coupled with the CSS:
#textarea {
display: none; /* hidden by default */
}
#textarea:target {
display: block; /* shown when a link targeting this id is clicked */
}
#textarea + ul.controls {
list-style-type: none; /* aesthetics only, adjust to taste, irrelevant to demo */
}
/* hiding the hide link when the #textarea is not targeted,
hiding the show link when it is selected: */
#textarea + ul.controls .hide,
#textarea:target + ul.controls .show {
display: none;
}
/* Showing the hide link when the #textarea is targeted,
showing the show link when it's not: */
#textarea:target + ul.controls .hide,
#textarea + ul.controls .show {
display: inline-block;
}
JS Fiddle demo.
Or, you could use a label and an input of type="checkbox":
Lorem ipsum dolor sit amet
<input id="textAreaToggle" type="checkbox" />
<p id="textarea">
<!-- This is where I want to additional text-->
All that delicious text is in here!
</p>
<label for="textAreaToggle">textarea</label>
<p>Here is some more text</p>
With the CSS:
#textarea {
/* hide by default: */
display: none;
}
/* when the checkbox is checked, show the neighbouring #textarea element: */
#textAreaToggle:checked + #textarea {
display: block;
}
/* position the checkbox off-screen: */
input[type="checkbox"] {
position: absolute;
left: -1000px;
}
/* Aesthetics only, adjust to taste: */
label {
display: block;
}
/* when the checkbox is unchecked (its default state) show the text
'Show ' in the label element: */
#textAreaToggle + #textarea + label::before {
content: 'Show ';
}
/* when the checkbox is checked 'Hide ' in the label element; the
general-sibling combinator '~' is required for a bug in Chrome: */
#textAreaToggle:checked ~ #textarea + label::before {
content: 'Hide ';
}
JS Fiddle demo.

Try to toggle height.
function toggleTextArea()
{
var limitedHeight = '40px';
var targetEle = document.getElementById("textarea");
targetEle.style.height = (targetEle.style.height === '') ? limitedHeight : '';
}

This is my pure HTML & Javascript solution:
var setHeight = function (element, height) {
if (!element) {;
return false;
}
else {
var elementHeight = parseInt(window.getComputedStyle(element, null).height, 10),
toggleButton = document.createElement('a'),
text = document.createTextNode('...Show more'),
parent = element.parentNode;
toggleButton.src = '#';
toggleButton.className = 'show-more';
toggleButton.style.float = 'right';
toggleButton.style.paddingRight = '15px';
toggleButton.appendChild(text);
parent.insertBefore(toggleButton, element.nextSibling);
element.setAttribute('data-fullheight', elementHeight);
element.style.height = height;
return toggleButton;
}
}
var toggleHeight = function (element, height) {
if (!element) {
return false;
}
else {
var full = element.getAttribute('data-fullheight'),
currentElementHeight = parseInt(element.style.height, 10);
element.style.height = full == currentElementHeight ? height : full + 'px';
}
}
var toggleText = function (element) {
if (!element) {
return false;
}
else {
var text = element.firstChild.nodeValue;
element.firstChild.nodeValue = text == '...Show more' ? '...Show less' : '...Show more';
}
}
var applyToggle = function(elementHeight){
'use strict';
return function(){
toggleHeight(this.previousElementSibling, elementHeight);
toggleText(this);
}
}
var modifyDomElements = function(className, elementHeight){
var elements = document.getElementsByClassName(className);
var toggleButtonsArray = [];
for (var index = 0, arrayLength = elements.length; index < arrayLength; index++) {
var currentElement = elements[index];
var toggleButton = setHeight(currentElement, elementHeight);
toggleButtonsArray.push(toggleButton);
}
for (var index=0, arrayLength=toggleButtonsArray.length; index<arrayLength; index++){
toggleButtonsArray[index].onclick = applyToggle(elementHeight);
}
}
You can then call modifyDomElements function to apply text shortening on all the elements that have shorten-text class name. For that you would need to specify the class name and the height that you would want your elements to be shortened to:
modifyDomElements('shorten-text','50px');
Lastly, in your your html, just set the class name on the element you would want your text to get shorten:
<div class="shorten-text">Your long text goes here...</div>

I hope this helps you. Here is the functionality:
When text characters is less than or equal to 12. Then it displays the whole text and also does not display the more/less button
When text characters is more than 12. Displays only 12 characters of the text and also a More button which when pressed, shows the whole text.
When the More button is pressed the button changes to Less
Read more string manipulation in w3schools: String Manipulation or
Mozila: String Manipulation
var startStatus = "less";
function toggleText() {
var text = "Here is the text that I want to play around with";
if (text.length > 12) {
if (startStatus == "less") {
document.getElementById("textArea").innerHTML = `${text.substring(0, 12)}...`;
document.getElementById("more|less").innerText = "More";
startStatus = "more";
} else if (startStatus == "more") {
document.getElementById("textArea").innerHTML = text;
document.getElementById("more|less").innerText = "Less";
startStatus = "less";
}
} else {
document.getElementById("textArea").innerHTML = text;
}
}
toggleText();
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<p id="textArea">
<!-- This is where i want text displayed-->
</p>
<span><a
id="more|less"
onclick="toggleText();"
href="javascript:void(0);"
></a
></span>
</div>
</body>
</html>

This should resolve your problem:
function toggleSeeMore() {
if(document.getElementById("textarea").style.display == 'none') {
document.getElementById("textarea").style.display = 'block';
document.getElementById("seeMore").innerHTML = 'See less';
}
else {
document.getElementById("textarea").style.display = 'none';
document.getElementById("seeMore").innerHTML = 'See more';
}
}
The complete working example is here: http://jsfiddle.net/akhikhl/zLA5K/

Hope this Code you are looking for
HTML:
<div class="showmore">
<div class="shorten_txt">
<h4> ##item.Title</h4>
<p>Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text Your Text </p>
</div>
</div>
SCRIPT:
var showChar = 100;
var ellipsestext = "[...]";
$('.showmore').each(function () {
$(this).find('.shorten_txt p').addClass('more_p').hide();
$(this).find('.shorten_txt p:first').removeClass('more_p').show();
$(this).find('.shorten_txt ul').addClass('more_p').hide();
//you can do this above with every other element
var teaser = $(this).find('.shorten_txt p:first').html();
var con_length = parseInt(teaser.length);
var c = teaser.substr(0, showChar);
var h = teaser.substr(showChar, con_length - showChar);
var html = '<span class="teaser_txt">' + c + '<span class="moreelipses">' + ellipsestext +
'</span></span><span class="morecontent_txt">' + h
+ '</span>';
if (con_length > showChar) {
$(this).find(".shorten_txt p:first").html(html);
$(this).find(".shorten_txt p:first span.morecontent_txt").toggle();
}
});
$(".showmore").click(function () {
if ($(this).hasClass("less")) {
$(this).removeClass("less");
} else {
$(this).addClass("less");
}
$(this).find('.shorten_txt p:first span.moreelipses').toggle();
$(this).find('.shorten_txt p:first span.morecontent_txt').toggle();
$(this).find('.shorten_txt .more_p').toggle();
return false;
});

<script type="text/javascript">
function showml(divId,inhtmText)
{
var x = document.getElementById(divId).style.display;
if(x=="block")
{
document.getElementById(divId).style.display = "none";
document.getElementById(inhtmText).innerHTML="Show More...";
}
if(x=="none")
{
document.getElementById(divId).style.display = "block";
document.getElementById(inhtmText).innerHTML="Show Less";
}
}
</script>
<p id="show_more1" onclick="showml('content1','show_more1')" onmouseover="this.style.cursor='pointer'">Show More...</p>
<div id="content1" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
</div>
if more div use like this change only 1 to 2
<p id="show_more2" onclick="showml('content2','show_more2')" onmouseover="this.style.cursor='pointer'">Show More...</p>
<div id="content2" style="display: none; padding: 16px 20px 4px; margin-bottom: 15px; background-color: rgb(239, 239, 239);">
</div>
demo
jsfiddle

I'm not an expert, but I did a lot of looking to implement this for myself. I found something different, but modified it to accomplish this. It's really quite simple:
The function takes two arguments, a div containing only the words "show more" [or whatever] and a div containing the originally hidden text and the words "show less." The function displays the one div and hides the other.
NOTE: If more than one show/hide on page, assign different ids to divs
Colors can be changed
<p>Here is text that is originally displayed</p>
<div id="div1">
<p style="color:red;" onclick="showFunction('div2','div1')">show more</p></div>
<div id="div2" style="display:none">
<p>Put expanded text here</p>
<p style="color:red;" onclick="showFunction('div1','div2')">show less</p></div>
<p>more text</p>
Here is the Script:
<script>
function showFunction(diva, divb) {
var x = document.getElementById(diva);
var y = document.getElementById(divb);
x.style.display = 'block';
y.style.display = 'none';
}
</script>

You can also use details HTML tag which does the work for you.
<details>
<summary>Epcot Center</summary>
<p>Epcot is a theme park at Walt Disney World Resort featuring exciting attractions, international pavilions, award-winning fireworks and seasonal special events.</p>
</details>
Source W3CSchool

Related

select text inside span on click

I want to get the text in which I clicked on, So if I click on word "mother" the log just show this word "mother", even if it's inside an span with another word,
I used this code but it doesn't even select the spans :
function getSelectedText(e) {
if(window.getSelection)
return console.log(window.getSelection().toString());
else if(document.getSelection)
return console.log(document.getSelection());
else if(document.selection)
return console.log(document.selection.createRange().text);
return console.log("");
}
document.body.onmouseup = getSelectedText;
<div class="destination">
<span class="word">sister mother</span>
<span class="word" >brother</span>
<span class="word" >father</span>
</div>
<h1>hi</h1>
The span-split option will work in all browsers and without using third-party libraries.
<body>
<style>
.container{
display: flex;
gap: 5px;
flex-wrap: wrap;
}
</style>
<div id="root" class = "container"></div>
<script>
var text = 'Soon after this, I started working with Kitty, who has volunteered at the shelter for years, so she knew all the lay of the land and was super helpful.'
var container = document.getElementById("root")
text.split(' ').forEach((word)=>{
var newWord = document.createElement("span")
newWord.innerText = word
newWord.className = 'myClass'
container.appendChild(newWord)
})
function handler(event) {
if (event.target.className === "myClass"){
console.log(event.target.textContent)
}
}
document.addEventListener('click',handler,false)
</script>
</body>
function highlight(span) {
span.classList.toggle("highlight");
//select the text and do what ever
var selectedText = span.innerHTML;
alert(selectedText);
}
.highlight {
background-color: lightblue;
}
<span onclick="highlight(this)">sister mother</span>
<span onclick="highlight(this)">brother</span>
<span onclick="highlight(this)">father</span>

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>

How to format a text in a div with jQuery/Css

I would like to display a text copied from a site, for example Wikipedia, in a div. This text has to be strictly without the tags that the computer copies with the text from wikipedia.
I think that the solution is to set a sort of formatting of the text but I don't know.
This is how it should be (Press OK). But I don't want to paste the text in the code, I have to paste the text in the textarea.
In fact if you try to paste something from Wikipedia in the textarea of this Jsfiddle you will see that the result is horrible and with all the html tags.
HTML:
<div id="faketxt" contenteditable></div>
<button id='btn'>OK</button>
<button class="fontStyle" onclick="document.execCommand( 'bold',false,null);" title="Bold Highlighted Text"><b>B</b>
</button>
<button class="fontStyle" onclick="document.execCommand( 'underline',false,null);"><u>U</u>
</button> <br>
<div id='boxes'>
</div>
CSS:
#faketxt {
-moz-appearance: textfield-multiline;
-webkit-appearance: textarea;
border: 1px solid gray;
height: 28px;
overflow: auto;
padding: 2px;
resize: both;
width: 400px;
}
.fakes{
width: 150px;
height: 300px;
font-size: 10px;
border-style: solid;
display:inline-block;
float: left;
}
#boxes{
display : flex;
display:inline-block;
}
jQuery:
$('#btn').click(function() {
var primo = document.getElementById('faketxt');
var wordLimit = 130;
var words = primo.innerHTML.replace(/(<([^>]+)>)/ig,"").split(/\s/);
if (words.length) {
var count = 0;
var div = createDiv();
var bold = false;
words.forEach(function(word) {
if (++count > wordLimit) {
count = 1;
div = createDiv();
}
if (div.innerHTML) {
div.append(' ');
}
if (word.indexOf('<b>') != -1) {
bold = true;
}
if (bold) {
$(div).html($(div).html() + '<b>' +
word + '</b>');
} else {
$(div).html($(div).html() +
word);
}
if (word.indexOf('</b>') != -1) {
bold = false;
}
});
}
});
function createDiv() {
div = document.createElement('div');
div.className = 'fakes';
document.getElementById('boxes').append(div);
return div;
}
innerHTML or jquery's $.html() will pull the content (including HTML) of an element. But textContent or jquery's $.text() will just get the text.
Instead of var words = primo.innerHTML have you tried using var words = primo.textContent or var words = $(primo).text()?
try using
words = primo.textContent.replace(/(<^>]+)>)/ig,"").split(/\s/);
instead of
words = primo.innerHTML.replace(/(<([^>]+)>)/ig,"").split(/\s/);
Rather than getting the innerHTML of the source, simply get the text content using either the javascript or JQuery text() functions.
So, given you are using jQuery, change your words variable to initialise as follows.
var words = $(primo).text().split(/\s/);

Box shadow won't "none" in JavaScript

My goal is to have a div that shows content and have a box shadow once clicked. Then I want to click on the div again to hide the content and box shadow. All is working great except for the box shadow that won't be hidden once its been clicked on in my second function that sets it to none. Why will this not work?
The HTML:
<div class="col-md-4 top" id="time">
<div class="clickme" id="clickme" onclick="clickme();
return false;">
<p>Click here for the time and date!</p>
</div>
</div>
The JavaScript:
function clickme(){
document.getElementById("clickme").style.display = 'none';
document.getElementById("time").style.boxShadow = "inset 6em 6em 6em #3B3130";
document.getElementById('time').innerHTML = "<h2 onclick='revert();''>It is " + theTime + " and the date is " + theDate + "</h2>";
}
function revert(){
document.getElementById('time').innerHTML = "";
document.getElementById("clickme").style.display = 'inline';
document.getElementById("time").style.boxShadow = 'none';
}
It's because you "destroy" the div #clickme when you modify the inner HTML of its parent.
See it working just fine when I moved the elements a bit:
function clickme() {
var theTime = 'some time';
var theDate = 'some date';
document.getElementById("clickme").style.display = 'none';
document.getElementById("time").style.boxShadow = "inset 6em 6em 6em #3B3130";
document.getElementById('time').innerHTML = "<h2 onclick='revert();''>It is " + theTime + " and the date is " + theDate + "</h2>";
}
function revert() {
document.getElementById('time').innerHTML = "";
document.getElementById("clickme").style.display = 'inline';
document.getElementById("time").style.boxShadow = 'none';
}
<div class="col-md-4 top" id="time"></div>
<div class="clickme" id="clickme" onclick="clickme();
return false;">
<p>Click here for the time and date!</p>
</div>
And don't forget - stuff like that is usually done using classes, not by applying styles directly.
#Shoms already identified the error in your code but I just want to give you a little more direction. I find it useful to move logic into the CSS wherever possible and just use javascript to add and remove classes. The advantage here is that you can easily fiddle with the CSS to change the look in different states without changing the javascript. Here is a possible solution.
var box = document.getElementById("box");
box.onclick = function() {
if (box.className.indexOf("clicked") == -1) {
box.className = "clicked";
} else {
box.className = "";
}
}
#box #time {
display: none;
}
#box.clicked {
box-shadow: 1em black;
}
#box.clicked #firstMessage {
display: none;
}
#box.clicked #time {
display: block;
}
<div id="box">
<p id="firstMessage">Click here for the time and date!</p>
<p id="time">Time to get a watch!</p>
</div>
Try this
document.getElementById("time").style.boxShadow = null;

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