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;
Related
I have a script that can add paragraphs to a div. These paragraphs have some text and a delete button in them. This delete button should be able to delete the paragraph its in including its text (so delete the whole paragraph), but it doesn't.
var elementCounter2 = 0;
function addElement2() {
elementCounter2++;
var p = document.createElement("p");
var node = document.createTextNode("This is element number " + elementCounter2);
p.setAttribute("id", "p" + elementCounter2);
p.appendChild(node);
p.innerHTML += ' <button id="del' + elementCounter2 + '" onclick="deleteElement2();">Delete this element.</button>';
document.getElementById("elements2").appendChild(p);
}
function deleteElement2() {
var p = document.getElementById("p" + elementCounter2);
var btn = document.getElementById("del" + elementCounter2);
//Button sees its own id and look for the corresponding p id, then deletes the paragraph.
}
.borderful {
border: solid 1px black;
margin: 10px;
padding: 10px;
}
<div class="borderful">
<p>Here is the second part</p>
<p>You can add elements here.</p>
<p>You can delete these aswell but differntly.</p>
<button onclick="addElement2();">Add an element.</button>
<div id="elements2"></div>
</div>
You can setup an event listener on each newly created paragraph (ditching the inline code) and forget about the counter (kept here to show the code working)
var elementCounter2 = 0;
function addElement2() {
elementCounter2++;
var p = document.createElement("p");
var node = document.createTextNode("This is element number " + elementCounter2);
p.setAttribute("id", "p" + elementCounter2);
p.appendChild(node);
p.innerHTML += ' <button>Delete this element.</button>';
document.getElementById("elements2").appendChild(p);
var el = document.getElementById("p" + elementCounter2);
el.addEventListener("click", deleteElement2, false);
}
function deleteElement2() {
this.remove()
}
.borderful {
border: solid 1px black;
margin: 10px;
padding: 10px;
}
<div class="borderful">
<p>Here is the second part</p>
<p>You can add elements here.</p>
<p>You can delete these aswell but differntly.</p>
<button onclick="addElement2();">Add an element.</button>
<div id="elements2"></div>
</div>
This should work
var elementCounter2 = 0;
function addElement2() {
elementCounter2++;
var p = document.createElement("p");
var node = document.createTextNode("This is element number " + elementCounter2);
p.setAttribute("id", "p" + elementCounter2);
p.appendChild(node);
p.innerHTML += ' <button id="del' + elementCounter2 + '" onclick="deleteElement2(this);">Delete this element.</button>';
document.getElementById("elements2").appendChild(p);
}
function deleteElement2(caller) {
// caller = button
document.getElementById("del" + caller.id.substr(3)).parentNode.remove();
}
.borderful {
border: solid 1px black;
margin: 10px;
padding: 10px;
}
<div class="borderful">
<p>Here is the second part</p>
<p>You can add elements here.</p>
<p>You can delete these aswell but differntly.</p>
<button onclick="addElement2();">Add an element.</button>
<div id="elements2"></div>
</div>
A simple approach is referring to the paragraph as a parent element instead of worrying how to reference it directly.
function deleteElement2() {
this.parentElement.remove();
}
However, adding the button as
p.innerHTML += ' <button id="del'+ elementCounter2 +'" onclick="deleteElement2();">Delete this element.</button>';
Is not a good practice since you are adding HTML element in Javascript, when you can go about doing this in Javascript only.
To learn more about your original question or how to do this in JS, refer to this very similar example given by CS50W lecture on YouTube: https://youtu.be/ZRV7JCXAFTs?t=2486
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/);
Have a problem and can't get to solve it. Tried to use QuerySelectorAll and comma separating with GetElementsByClassName, but that didn't work, so I am wondering how to solve this problem.
I have this HTML:
<div class="area">Test title
<div class="some content" style="display: none">blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
<div class="area">
Test title
<div class="some content">
blablbala
<input></input>
</div>
<div class="two">This should be clickable too</div>
</div>
JS:
function areaCollapse() {
var next = this.querySelector(".content");
if (this.classList.contains("open")) {
next.style.display = "none";
this.classList.remove("open");
} else {
next.style.display = "block";
this.classList.add("open");
}
}
var classname = document.getElementsByClassName("area");
for (var i = 0; i < classname.length; i++) {
classname[i].addEventListener('click', areaCollapse, true);
}
http://jsfiddle.net/1BJK903/nb1ao39k/6/
CSS:
.two {
position: absolute;
top: 0;
}
So now, the div with classname "area" is clickable. I positioned the div with class "two" absolute and now the whole div is clickable, except where this other div is. If you click on the div with classname "two", it doesn't work (it does not collapse or open the contents). How can I make this work, without changing the structure?
One way is using a global handler, where you can handle more than one item by checking its id or class or some other property or attribute.
Below snippet finds the "area" div and pass it as a param to the areaCollapse function. It also check so it is only the two or the area div (colored lime/yellow) that was clicked before calling the areaCollapse.
Also the original code didn't have the "open" class already added to it (the second div group), which mean one need to click twice, so I change the areaCollapse function to check for the display property instead.
function areaCollapse(elem) {
var next = elem.querySelector(".content");
if (next.style.display != "none") {
next.style.display = "none";
} else {
next.style.display = "block";
}
}
window.addEventListener('click', function(e) {
//temp alert to check which element were clicked
//alert(e.target.className);
if (hasClass(e.target,"area")) {
areaCollapse(e.target);
} else {
//delete next line if all children are clickable
if (hasClass(e.target,"two")) {
var el = e.target;
while ((el = el.parentElement) && !hasClass(el,"area"));
if (targetInParent(e.target,el)) {
areaCollapse(el);
}
//delete next line if all children are clickable
}
}
});
function hasClass(elm,cln) {
return (" " + elm.className + " " ).indexOf( " "+cln+" " ) > -1;
}
function targetInParent(trg,pnt) {
return (trg === pnt) ? false : pnt.contains(trg);
}
.area {
background-color: lime;
}
.two {
background-color: yellow;
}
.area:hover, .two:hover {
background-color: green;
}
.some {
background-color: white;
}
.some:hover {
background-color: white;
}
<div class="area">Test title clickable 1
<div class="some content" style="display: none">blablbala NOT clickable 1
</div>
<div class="two">This should be clickable too 1</div>
</div>
<div class="area">Test title clickable 2
<div class="some content">blablbala NOT clickable 2
</div>
<div class="two">This should be clickable too 2</div>
</div>
<div class="other">This should NOT be clickable</div>
You need to find your two elements while you're binding classname, and bind that as well.
var classname = document.getElementsByClassName("area");
for(var i=0; i < classname.length; i++){
classname[i].addEventListener('click', areaCollapse, true);
var twoEl = classname[i].getElementsByClassName("two")[0];
twoEl.addEventListener('click', function(e) { console.log('two clicked'); });
}
If you want to use jQuery:
$('.two').click(function(){
//action here
});
<body>
<div id = "SiteContainer">
<div id = "NavigationButtons"></div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition();">x</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition();">y</div>
<div id = "VideoWrapper">
<div id = "SlideShowItem">
<img src="Images/A.png" alt="A"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/B.png" alt="B"></img>
</div>
<div id = "SlideShowItem">
<img src="Images/C.png" alt="C" ></img>
</div>
</div>
</div>
</div>
<script>
var wrapper = document.querySelector("#VideoWrapper");
function setPosition(e)
{
if(e.target.name = "forward")
{
if!(wrapper.style.left = "-200%")
{
wrapper.style.left = wrapper.style.left - 100%;
}
}
else
{
if(e.target.name = "back")
{
if!(wrapper.style.left = "0%")
{
wrapper.style.left = wrapper.style.left + 100%;
}
}
}
}
</script>
</body>
Hi, I am very new to javascript. What I am trying to do, is change the x-position of a div when another div (NavigationForward or NavigationBackward) is clicked. However it does not appear to do anything at all. Basically if the div with name forward is clicked, I want to translate the VideoWrapper -100% from it's current position and +100% when "back". The css div itself VideoWrapper has a width of 300%. Inside this div as you can see is a SlideShowItem which is what will change. Perhaps I am adding and subtracting 100% the wrong way?
EDIT:
Thanks everyone for helping me out with this...I had just one more query, I am trying to hide the arrows based on whether the wrapper is at the first slide or the last slide. If its on the first slide, then I'd hide the left arrow div and if it's on the last, I'd hide the right arrow, otherwise display both of em. Ive tried several ways to achieve this, but none of em work, so Ive resorted to using copies of variables from the function that works. Even then it does not work. It appears that my if and else if statements always evaluate to false, so perhaps I am not retrieving the position properly?
function HideArrows()
{
var wrapper2 = document.getElementById("VideoWrapper");
var offset_x2 = wrapper2.style.left;
if(parseInt(offset_x2,10) == max_x)
{
document.getElementById("NavigationForward").display = 'none';
}
else if(parseInt(offset_x2,10) == min_x)
{
document.getElementById("NavigationBackward").display = 'none';
}
else
{
document.getElementById("NavigationForward").display = 'inline-block';
document.getElementById("NavigationBackward").display = 'inline-block';
}
}
//html is the same except that I added a mouseover = "HideArrows();"
<div id = "ShowReelContainer" onmouseover="HideArrows();">
To achieve this type o slider functionality your div VideoWrapper must have overflow:hidden style, and your SlideShowItemdivs must have a position:relative style.
Then to move the slides forward or backward you can use the style left which allows you to move the divs SlideShowItem relative to it's parent VideoWrapper.
I've tested this here on JSFiddle.
It seems to work as you described in your question, although you may need to do some adjustments, like defining the width of your slides, how many they are and so on.
For the sake of simplicity, I defined them as "constants" on the top of the code, but I think you can work from that point on.
CSS
#VideoWrapper{
position:relative; height:100px; white-space:nowrap;width:500px;
margin-left:0px; border:1px solid #000; overflow:hidden; }
.SlideShowItem{
width:500px; height:100px;display:inline-block;position:relative; }
#NavigationForward, #NavigationBackward{
cursor:pointer;float:left; background-color:silver;margin-right:5px;
margin-bottom:10px; text-align:center; padding:10px; }
HTML
<div id = "SiteContainer">
<div id = "NavigationButtons">
</div>
<div id = "ShowReelContainer">
<div id= "NavigationBackward" name = "back" onclick="setPosition('back');">prev</div>
<div id= "NavigationForward" name = "forward" onclick="setPosition('forward');">next</div>
<div style="clear:both;"></div>
<div id = "VideoWrapper">
<div class= "SlideShowItem" style="background-color:blue;">
Slide 1
</div>
<div class = "SlideShowItem" style="background-color:yellow;">
Slide 2
</div>
<div class = "SlideShowItem" style="background-color:pink;">
Slide 3
</div>
</div>
</div>
</div>
JavaScript
var unit = 'px'; var margin = 4; var itemSize = 500 + margin; var itemCount = 3; var min_x = 0; var max_x = -(itemCount-1) * itemSize;
function setPosition(e) {
var wrapper = document.getElementById("VideoWrapper");
var slides = wrapper.getElementsByTagName('div');
var offset_x = slides[0].style.left.replace(unit, '');
var curr_x = parseInt(offset_x.length == 0 ? 0 : offset_x);
if(e == "forward")
{
if(curr_x <= max_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + -itemSize) + unit;
}
else if(e == "back")
{
if(curr_x >= min_x)
return;
for(var i=0; i<slides.length; i++)
slides[i].style.left= (curr_x + itemSize) + unit;
} }
After you analyze and test the code, I don't really know what's your purpose with this, I mean, you maybe just playing around or trying to develop something for a personal project, but if you are looking for something more professional avoid to create things like sliders on your own, as there are tons of plugins like this available and well tested out there on the web.
Consider using jQuery with NivoSlider, it works like a charm and is cross browser.
I would recommend using jQuery, this will reduce your coding by quite a bit. Can read more here: http://api.jquery.com/animate/
I've created a simple fiddle for you to take a look at. This example uses the .animate() method to reposition two div elements based on the CSS 'left' property.
CSS:
#container {
position: absolute;
left: 1em;
top: 1em;
right: 1em;
bottom: 1em;
overflow: hidden;
}
#one, #two {
position: absolute;
color: white;
}
#one {
background: pink;
width: 100%;
top:0;
bottom:0;
}
#two {
background: blue;
width: 100%;
left: 100%;
top:0;
bottom:0;
}
HTML:
<div id="container">
<div id="one">Div One</div>
<div id="two">Div Two</div>
</div>
JavaScript/jQuery:
var one, two, container;
function animateSlides(){
one.animate({
left : '-100%'
}, 1000, function(){
one.animate({
left : 0
}, 1000);
});
two.animate({
left : 0
}, 1000, function(){
two.animate({
left:'100%'
}, 1000);
});
};
$(function(){
one = $('#one');
two = $('#two');
container = $('#container');
setInterval(animateSlides, 2000);
});
JSFiddle Example: http://jsfiddle.net/adamfullen/vSSK8/3/
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