Wordpress: Read More Text For Mobile not working - javascript

I'm using the read more script and it will display a button at the end with text showing less. the script is working fine but I've used the script in various sections and using the section class I've updated the read-more-text length as per my requirement. But when I show less it adds the inline CSS for the height of 100px, which is creating a problem for mobile devices for mobile to display the first paragraph I have added a large height, but after showing less it adds the 100px height as in line height.
Here is the script.
jQuery('.read-more__btn').click(function(){
if(jQuery(this).siblings(".read-more__text").hasClass("show")){
jQuery(this).removeClass("up");
jQuery(this).text("Read More");
jQuery(this).siblings(".read-more__text").animate({
height: '100px'
}, 1000);
jQuery(this).siblings(".read-more__text").removeClass("show");
} else {
jQuery(this).siblings(".read-more__text").addClass("show");
jQuery(this).siblings(".read-more__text").animate({
height: jQuery(this).siblings(".read-more__text").get(0).scrollHeight
}, 1000, function(){
jQuery(this).height('auto');
});
jQuery(this).addClass("up");
jQuery(this).text("Read Less");
}
});

Please check below some basic examples for read more & less, might be it will help full for you.
<h2>Read More Read Less Button</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction()" id="myBtn">Read more</button>
<script>
function myFunction() {
var dots = document.getElementById("dots");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
</script>
And here you can check example links

Related

Reusing a Javascript function?

I have this simple read more JS function. I want to reuse it, what's the best practice for this? For example, below, I have two read more buttons but I have to copy paste the function and some number to it to use it. Not the cleanest way, what's a better way around this?
function myFunction() {
var dots = document.getElementById("dots");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
function myFunction2() {
var dots = document.getElementById("dots2");
var moreText = document.getElementById("more2");
var btnText = document.getElementById("myBtn2");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
#more {display: none;}
#more2 {display: none;}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction()" id="myBtn">Read more</button>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel<span id="dots2">...</span><span id="more2">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction2()" id="myBtn2">Read more</button>
First, when repeating behavior you should refrain from attempting to use id attributes since (as you know) they must be unique. Additionally, it leads to naming things without much meaning (thing1, thing2 etc).
One technique is to use the class attribute.
Each event allows access to the target of the event. We can find the paragraph to effect using the previousElementSibling to find the <p>.
From there, we can use that node to query for the .dots and .more classes and change them as needed.
Since the button is the target of the event, we just change the button text directly.
EDIT: Thanks #Carston for the previousElementSibling hint.
function myFunction(e) {
const paragraph = e.target.previousElementSibling;
var dots = paragraph.querySelector('.dots');
var moreText = paragraph.querySelector(".more");
if (dots.style.display === "none") {
dots.style.display = "inline";
e.target.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
e.target.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
.more {display: none;}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(event)">Read more</button>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel<span class="dots">...</span><span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(event)">Read more</button>
You could use a function parameter to dynamically add a suffix to your ids :
function myFunction(suffix) {
var dots = document.getElementById("dots" + suffix);
var moreText = document.getElementById("more" + suffix);
var btnText = document.getElementById("myBtn" + suffix);
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
#more {display: none;}
#more2 {display: none;}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction('')" id="myBtn">Read more</button>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel<span id="dots2">...</span><span id="more2">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction('2')" id="myBtn2">Read more</button>
Or 3 parameters corresponding to the ids :
function myFunction(dotsId, moreTextId, btnTextId) {
var dots = document.getElementById(dotsId);
var moreText = document.getElementById(moreTextId);
var btnText = document.getElementById(btnTextId);
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
#more {display: none;}
#more2 {display: none;}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction('dots','more','myBtn')" id="myBtn">Read more</button>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel<span id="dots2">...</span><span id="more2">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction('dots2','more2','myBtn2')" id="myBtn2">Read more</button>
use template literals like this:
function myFunction(number) {
var dots = document.getElementById(`dots${number}`);
var moreText = document.getElementById(`more${number}`);
var btnText = document.getElementById(`myBtn${number}`);
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
<button onclick="myFunction('')" id="myBtn">Read more</button>
<button onclick="myFunction2('2')" id="myBtn2">Read more</button>
I guess this answer was not really called for. In my opinion #RandyCasburn already nailed it. However, here is another version that works with even less html to put in place to create unfoldable sections.
By placing a <span class="more"></span> within a paragraph this section is marked to be "unfoldable". The first part of my script adds the three dots and a "Read more" button and makes the span's original content invisible.
The delegated click event handler then does all the work:
// prepare document once (put "..." and buttons in place):
document.querySelectorAll(".more").forEach(el=>{
el.dataset.html=el.innerHTML;
el.textContent="...";
const btn=document.createElement("button");
btn.className="morebtn";
btn.textContent="Read more";
el.closest("p").after(btn);
})
// delegated event attachment:
document.body.onclick=e=>{
if (e.target.className==="morebtn"){
const mor = e.target.previousElementSibling.querySelector(".more");
[mor.innerHTML,mor.dataset.html]=[mor.dataset.html,mor.innerHTML];
e.target.innerHTML = mor.textContent==="..."?"Read more":"Read less";
}
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, naliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida isi lorem egestas vitae scel<span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<p>And another paragraph with more nonsensical text that will only <span class="more">be shown completely, once the "Read more" button was hit.</span></div>

Read More collapse script change

I want to be able to collapse each "read-more" for its own section. The code is borrowed from w3schools and trying to modify by adding a second section. But the second button expands s the first text. I understand (from reading on other sections) I will have to modify the id for elements so that each section is self-contained. What do I need to modify this behavior? This is a new area for me, be gentle ...
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#more {display: none;}
</style>
</head>
<body>
<h2>One</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction()" id="myBtn">Read more</button>
<h2>Two</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span id="dots">...</span><span id="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction()" id="myBtn">Read more</button>
<script>
function myFunction() {
var dots = document.getElementById("dots");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
</script>
</body>
</html>
You have to change all your IDs with classes, for example, 'cause IDs must be unique in a page.
After that, a solution could be to insert the 2 texts in 2 divs, passing this element to the myFunction to select the right parent box to work on.
function myFunction(elmnt) {
var myID = elmnt.parentNode;
var dots = myID.getElementsByClassName("dots")[0];
var moreText = myID.getElementsByClassName("more")[0];
var btnText = myID.getElementsByClassName("myBtn")[0];
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
.more {display: none;}
<div>
<h2>One</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(this)" class="myBtn">Read more</button>
</div>
<div>
<h2>Two</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(this)" class="myBtn">Read more</button>
</div>
EDIT 1
You have to change all IDs 'cause they must be unique in a page. You can't use them for another textbox. So if you want to use 2,3,4... several textboxes, you have to transform all IDs in classes.
In my example, I changed a little the script to manage those classes, not IDs. Copy and paste my code in w3school snippet, click "Run" and you'll see it work. I changed the name of variable myID in parentElement so maybe it is more clear to you.
The script var dots = parentElement.getElementsByClassName("dots")[0]; means find first element that has a class named "dots" in my parentElement (i.e. the external div that I added)
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.more {display: none;}
</style>
</head>
<body>
<div>
<h2>One</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(this)" class="myBtn">Read more</button>
</div>
<div>
<h2>Two</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span class="dots">...</span><span class="more">erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>
<button onclick="myFunction(this)" class="myBtn">Read more</button>
</div>
<script>
function myFunction(elmnt) {
var parentElement = elmnt.parentNode;
var dots = parentElement.getElementsByClassName("dots")[0];
var moreText = parentElement.getElementsByClassName("more")[0];
var btnText = parentElement.getElementsByClassName("myBtn")[0];
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "Read more";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "Read less";
moreText.style.display = "inline";
}
}
</script>
</body>
</html>

Eventlistener function requires two clicks

I just started JS and trying to get a button which opens a block of text and with this same button you can close the block. All works fine but the first click is doing the focus and second click is opening the block of text. Block of text needs to open on the first click.
Hope you can help me out with plain JS...Thanks!
document.getElementById("homeBtn").addEventListener("click", function(){
var x = document.getElementById("parText");
var y = document.getElementById("homeBtn");
if (x.style.display === "none") {
x.style.display = "block";
y.innerHTML = "Sluiten";
} else {
x.style.display = "none";
y.innerHTML = "Lees verder...";
}
});
HTML:
<div>
<button type="button" id="homeBtn">Lees verder...</button>
</div>
<div id="parText">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Etiam sed leo felis. Maecenas tincidunt orci id orci vulputate congue.
Aliquam in molestie tortor. Sed erat felis, tincidunt id commodo sit amet,
dignissim fringilla metus. Proin porta, justo eget sollicitudin hendrerit,
sapien ligula imperdiet erat, vel hendrerit odio quam ut mauris.
Etiam laoreet justo massa, ac pretium sem pharetra at. Nullam ut felis orci.
Duis faucibus mauris libero, at semper nulla finibus vitae. In ut ex justo.
</p>
</div>
You need to set the display to none first. When your code is running it goes to the else part and then it is setting the display to none, so nothing is happening. When you click again the if statement is now true as the display is set to none and the code works. I have fixed your code. Check the snippet.
var y = document.getElementById("homeBtn");
var x = document.getElementById("parText");
x.style.display = "none";
y.addEventListener("click", function(){
if (x.style.display === "none") {
x.style.display = "block";
y.innerHTML = "Sluiten";
} else {
x.style.display = "none";
y.innerHTML = "Lees verder...";
}
});
<button type="button" id="homeBtn">Lees verder...</button>
<div id="parText">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Etiam sed leo felis. Maecenas tincidunt orci id orci vulputate congue.
Aliquam in molestie tortor. Sed erat felis, tincidunt id commodo sit amet,
dignissim fringilla metus. Proin porta, justo eget sollicitudin hendrerit,
sapien ligula imperdiet erat, vel hendrerit odio quam ut mauris.
Etiam laoreet justo massa, ac pretium sem pharetra at. Nullam ut felis orci.
Duis faucibus mauris libero, at semper nulla finibus vitae. In ut ex justo.
</p>
</div>

Hide JavaScript at a smaller screen

I am setting up my website to be responsive, and I want to know how to hide my livechat JavaScript when the screen size is smaller than 700px.
My current livechat JavaScript is ,
<script type="text/javascript">
function wsa_include_js(){
var wsa_host = (("https:" == document.location.protocol) ? "https://" : "http://");
var js = document.createElement("script");
js.setAttribute("language", "javascript");
js.setAttribute("type", "text/javascript");
js.setAttribute("src",wsa_host + "tracking-v3.websitealive.com/3.0/?objectref=wsa3&groupid=12581&websiteid=0");
document.getElementsByTagName("head").item(0).appendChild(js);
}
if (window.attachEvent)
window.attachEvent("onload", wsa_include_js);
else if (window.addEventListener)
window.addEventListener("load", wsa_include_js, false);
else
document.addEventListener("load", wsa_include_js, false);
</script>
Can someone please show me how. Thanks
This can actually be solved pretty easily with CSS media queries, however I need to know how the LiveChat is added to the HTML in order to give you a good answer.
What you want to do is take the class or ID of the div that holds the chat window and add the following to your CSS file:
#media screen and (max-width: 700px) {
#LiveChatContainerID { display: none; }
}
or
#media screen and (max-width: 700px) {
.LiveChatContainerClass { display: none; }
}
If LiveChat requires you to add an iframe to your site, just wrap the iframe in div tags with a unique ID or class and use the above in your CSS.
EDIT:
After seeing your site, I think I have a solution that will work fine:
#media screen and (max-width: 700px) {
.wsa_window, .wsa_window_close { display: none !important; }
}
The '!important' is needed to overwrite the style the javascript puts on the elements directly, but doing this in the inspector seemed to work fine without removing anything else on the page.
Hope this helps!
check this out it will help you. Its easy with JFiddle
This particular code changes color on size change so you can simply restructure it for your purpose. Test what you want to achieve right there in the code editor and see your result.
function red() {
$('div').css('background','#B60C0C')
.text('Screen Size RED');
}
function orange() {
$('div').css('background','#EBAE10')
.text('Screen Size ORANGE');
}
function green() {
$('div').css('background','#83ba2b')
.text('Screen Size GREEN');
}
var bounds = [
{min:0,max:500,func:red},
{min:501,max:850,func:orange},
{min:851,func:green}
];
var resizeFn = function(){
var lastBoundry; // cache the last boundry used
return function(){
var width = window.innerWidth;
var boundry, min, max;
for(var i=0; i<bounds.length; i++){
boundry = bounds[i];
min = boundry.min || Number.MIN_VALUE;
max = boundry.max || Number.MAX_VALUE;
if(width > min && width < max
&& lastBoundry !== boundry){
lastBoundry = boundry;
return boundry.func.call(boundry);
}
}
}
};
$(window).resize(resizeFn());
$(document).ready(function(){
$(window).trigger('resize');
});
I'm also not sure how you have added your chat into you page but if you have it in a div-tag you could hide that div on smaller screens.
You could do it with a script like in this jsFiddle but I think it's better to use CSS media queries as Oceanity answered.
In the fiddle you can easily test it by changing the size of the output section with the handle at the center.
(The size is set to 400px in the demo for easier testing in jsFiddle.)
For checking the size I have used a script from this SO question. I'm doing the size checking in onload- and onresize event.
function getViewPortSize()
{ // source code form here https://stackoverflow.com/questions/10653019/how-to-find-the-screen-width-and-apply-it-to-a-particular-css
var viewportwidth;
var viewportheight;
// Standard browsers
if (typeof window.innerWidth != 'undefined')
{
viewportwidth = window.innerWidth,
viewportheight = window.innerHeight
}
// IE6
else if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0)
{
viewportwidth = document.documentElement.clientWidth,
viewportheight = document.documentElement.clientHeight
}
//Older IE
else
{
viewportwidth = document.getElementsByTagName('body')[0].clientWidth,
viewportheight = document.getElementsByTagName('body')[0].clientHeight
}
return { width: viewportwidth, height: viewportheight};
}
var hideChat = function(evt) {
console.log(getViewPortSize().width);
if ( getViewPortSize().width < 400) {
//console.log('hide div now');
document.getElementById('chatArea').style = 'display: none';
}
else {
document.getElementById('chatArea').style = 'display: block';
}
};
window.onresize = function(evt) {
console.log(evt);
hideChat(evt);
};
window.onload = function(evt) {
console.log(evt);
hideChat(evt);
};
<div id="chatArea">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. Maecenas tempus, tellus eget condimentum rhoncus, sem quam semper libero, sit amet adipiscing sem neque sed ipsum. Nam quam nunc, blandit vel, luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus. Donec vitae sapien ut libero venenatis faucibus. Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit amet nibh. Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,
</div>

Toggle an Image on Click

I'm trying to toggle an image on Click. It's partially working but also partially not :'(
Demo: http://jsfiddle.net/Tqwdh/4/.
When I click the large image, the smaller image changes (from 50x50 to 151x151) - hurrah!
But when I click the 'Read more' text, the small image remains the same image. The small, nested image needs to change when I click the 'Read more' text.
Can anyone show me how I can resolve this?
I've attached my jQuery:
$(function(){
// The height of the content block when it's not expanded
var adjustheight = 130;
// The "more" link text
var moreText = "Click to read more...";
// The "less" link text
var lessText = "Click to read less...";
// Sets the .more-block div to the specified height and hides any content that overflows
$(".more-less .more-block").css('height', adjustheight).css('overflow', 'hidden');
// The section added to the bottom of the "more-less" div
$(".more-less").append('<p style="display:block;margin-top:8px"></p>');
$("a.adjust").text(moreText);
$(".adjust").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
});
$(function(){
$('img').click(function(){
$(this).closest('article').find('.adjust').click();
});
});
$(function(){
$("article").click(function(){
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50'
)
)
});
});
and my HTML:
<article id="post-5" >
<div class="more-less">
<div class="more-block">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam purus, lacinia eget placerat sit amet, bibendum nec nisl. Curabitur a mattis ipsum. Praesent quis nisi in purus malesuada rhoncus. Pellentesque ut quam eget libero congue lobortis. Nunc sed quam ac erat lobortis eleifend. Donec elementum sodales cursus. Aliquam porttitor massa nisi, in laoreet turpis. Sed consequat condimentum lorem ut dignissim. Sed hendrerit mauris ut massa fermentum laoreet. Pellentesque a leo vitae enim dictum lobortis. Praesent commodo feugiat velit iaculis malesuada.</p>
<p>Praesent sem lectus, ullamcorper eget ullamcorper a, congue vel nisl. Nullam volutpat leo vel dui venenatis dapibus. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus ac scelerisque lorem. Ut blandit magna eu turpis posuere gravida. Fusce egestas risus in libero ullamcorper sagittis. Vestibulum molestie metus vitae quam dignissim consequat. Vivamus id tellus id lorem consectetur iaculis sit amet interdum ante. Quisque lacinia tellus id mi tincidunt fermentum dignissim velit laoreet. Quisque scelerisque nunc iaculis nisi varius ultrices.</p>
<p>Phasellus id elit ac lacus faucibus ullamcorper. Etiam ullamcorper pretium tellus, ut pharetra ante pulvinar vel. Sed neque diam, semper vel rhoncus non, congue ut sapien. Integer a mi eget libero elementum lobortis. Donec hendrerit egestas ligula sit amet eleifend. Curabitur pharetra venenatis tempor. Quisque pulvinar malesuada justo, ut euismod arcu pharetra vitae. Cras lobortis, ligula id euismod euismod, ipsum risus varius urna, faucibus gravida lectus mi nec nulla. Fusce eleifend fringilla nibh ut vulputate. Vivamus sagittis leo metus. Etiam facilisis convallis lacus adipiscing hendrerit. Duis ultricies euismod libero, nec blandit est semper a. Phasellus sit amet justo sed quam elementum lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<p>
<img src="http://placehold.it/50x50" class="small" style="position:absolute;margin-left: 240px;margin-top: 127px;" />
<img src="http://placehold.it/300x187" alt="News Item 1" width="300" height="187" />
</p>
</article>
Many thanks for any pointers.
So, if I have understood you correctly, all you've got to do is,
Change this
$("article").click(function() {
//your code here
});
to,
$("article, .adjust").click(function() {
//your code here
});
Check the fiddle here
EDIT:
Changed a couple of things to match what you needed,
1) Change this,
$(this).parents('article').find('.adjust').click();
to,
$(this).parents('article').find('.adjust').trigger('click');
as the latter is a proper way to trigger an event.
2) Change in the image swap function,
$("article, .adjust").click(function() {
/*Save references in variables*/
var imgToSwap = $(this).parents("article").find("img.small");
var img_small = 'http://placehold.it/50x50';
var img_large = 'http://placehold.it/151x151';
imgToSwap.attr('src', (imgToSwap.attr('src') == img_small ? img_large : img_small));
});
Using $(this) will help you get the image in the right context.
Check the fiddle test here
It looks like you have a few problems here. I don't see that you've applied the adjust class to any element in your HTML. I also see that CSS is applied directly in JavaScript. (Why not use a .css file?)
This part of the code looks very nice:
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50' ))
This is good use of the ternary operator.
My I suggest that you use this code as the click handler on a.adjust, assuming that the link that expands the image is supposed to be decorated with the adjust class?
var changeImage = function() {
$("img.small").attr('src',
($("img.small").attr('src') == 'http://placehold.it/50x50'
? 'http://placehold.it/151x151'
: 'http://placehold.it/50x50' ))
});
$('a.adjust').click(changeImage);
$('article').click(changeImage);
I hope this helps. If the question were written more precisely, it might be helpful.

Categories