I am trying to get this collapsible to function normally and show the first set of information when the page is loaded, make it disappear when the user presses "read more", and show new information.
<script>
var coll = document.getElementsByClassName("collapsible");
var i;
for (i = 0; i < coll.length; i++) {
coll[i].addEventListener("click", function () {
this.classList.toggle("active");
var content = this.nextElementSibling;
if (content.style.display === "block") {
content.style.display = "none";
} else {
content.style.display = "block";
}
});
}
function display() {
var x = document.getElementById("cover");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
You are attaching the onclick=display() to all of your list elements. GetElementById is going to return the first element with the given id, in this case it's always targeting your first cover (if you're triggering that elsewhere in your script). So since every 'read more' list element has the onclick function calling display(), it is always hitting your first element (because it's the first element with the respective id). What you could do instead pass in the event then use 'closest' and pass in the id there (if your intention is to hide the image as well). If not you can remove the display() on the onclick there.
The other elements are working as expected but you don't see it because your css on the enclosing container is hiding it (if you check your inspector you will notice the css being set as expected). You might want to add an overflow scroll to scroll within the container limits to see your expanded data, or use something like css flex with minimum height in order to expand the container to see your read more data
Related
This question already has answers here:
Show/hide 'div' using JavaScript
(15 answers)
Closed last month.
I've created a script that hides a DIV Class if it contains the text "No Event Found" or "Error". This part is working great, however when this happens I would like a hidden DIV ID to load in it's place. (#brxe-akqmjs)
<script>
const divs = document.getElementsByClassName('etn-not-found-post');
for (let x = 0; x < divs.length; x++) {
const div = divs[x];
const content = div.textContent.trim();
if (content == 'No Event Found' || content == 'Error') {
div.style.display = 'none';
}
}
</script>
How do I go about getting this to load correctly? The DIV I want to show is set to display:none.
Many thanks in advance.
I have tried adding if statements but this only results in the original code breaking.
You can simply using jquery hide() and show() method to hide and show the content. Here I rewrite the function in jquery format.
<script>
const divs = $('.etn-not-found-post');
for (let x = 0; x < divs.length; x++) {
const div = divs[x];
const content = div.textContent.trim();
if (content == 'No Event Found' || content == 'Error') {
div.hide();
}else{
div.show();
}
}
</script>
It depends on how that hidden DIV with ID been implemented.
Let me try to cover two approaches:
DIV is hidden with css using display: none;
DIV is hidden using attribute hidden
For both cases, first get the element reference by ID. For e.g.
var divWithID = document.getElementById("divWithID");
Now for case 1,update the style property.
dovWithId.style.display = "block";
For case 2, set the hidden attribute value to false
divWithID.setAttribute("hidden", false);
Hope this helps and clarifies your question.
I'm trying to have a couple of buttons to show and hide some pictures, I have gotten it to somewhat work, but when I start the webpage the pictures are already shown, when I try make them invisible at start. I have tried swapping the "block" and "none" sentences in the function, but it just made the button less responsive.
javascript part:
function bassnectar() {
var x = document.getElementById("myDIV3");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
html part:
<button onclick="bassnectar()">Bassnectar</button>
<div id="myDIV3">
<img src="/images/bassnectar.jpg">
</div>
What you’re missing is that you’re assuming that block elements have a default display value of block. Which would be intuitive.
Such is not the case though.
The initial value of display is the browser’s default. If you query the value of the display property on a new HTML element, you’ll get an empty string.
It doesn’t return block until you explicitly set its display to block.
Edit:
It's important to note that setting a value in CSS doesn't change the behavior. If you set a div to be display block in CSS, it will still return an empty string if you query it.
Here's a working example:
var block = document.createElement("div");
var inline = document.createElement("span");
console.log("Initial display values:")
console.log(`block.style.display: ${block.style.display}`);
console.log(`inline.style.display: ${inline.style.display}`);
block.style.display = "block";
inline.style.display = "inline";
console.log("\nAfter setting them explicitly:")
console.log(`block.style.display: ${block.style.display}`);
console.log(`inline.style.display: ${inline.style.display}`);
div {
display: block !important;
}
I had this code, that works ok to show/hide a second element by clicking the first one:
<script>
var acc = document.getElementsByClassName("movs-header");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
var x = this.nextElementSibling;
if (x.style.display === "block") {
x.style.display = "none";
} else {
x.style.display = "block";
}
}
}
</script>
And this is the structure (they are repeating elements in a php system):
<div id="frm_container_[id]" class="movs-box">
<div class="movs-header">
some content here, clickable to show-hide the next sibling div
</div>
<div class="movs-body">
this content will show and hide
</div>
</div>
Now, I need to add this link inside a div with a class="movs-editlink", which has to be outside the movs-box div to refer the id "frm_container", in order to work.
Then the structure will be:
<div id="frm_container_[id]" class="movs-box">
<div class="movs-header">
some content here, clickable to show-hide the next sibling div
</div>
<div class="movs-body">
this content will show and hide
</div>
</div>
<div class="movs-editlink">[editlink label="edit" prefix="frm_container_"]</div> <!-- this div to show and hide along -->
(please don't mind the shortcode, it works fine)
What I need is to show/hide the last div with the same javascript code (when I click the "movs-header" div, but I fail to refer to "this.className", my guess was:
<script>
var acc = document.getElementsByClassName("movs-header");
var i;
for (i = 0; i < acc.length; i++) {
acc[i].onclick = function(){
this.classList.toggle("active");
var x = this.nextElementSibling;
var xedit = this.getElementsByClassName("movs-editlink").classname;
if (x.style.display === "block") {
x.style.display = "none";
xedit.style.display = "none";
} else {
x.style.display = "block";
xedit.style.display = "block";
}
}
}
</script>
I believe this is not working because the last div is outside the scope of "this", then I think I need to find the NEXT div in the structure with the class "movs-link" to be included in the display toggle, am I right? But I can't find how. Please help.
Based on your markup, rather than getElementsByClassName from this, do it with this.parentNode.nextElementSibling
var xedit = this.parentNode.nextElementSibling;
Or with jquery's nextUntil
var xedit = $(this).parent().nextUntil( "movs-editlink" );
The popup in my fiddle works great except if i want to make more than one, i have to create multiple divs with multiple images and multiple IDs, which works fine but is time consuming and messy.
Edit: Each popup will have a different image
My goal is to:
1) Still create multiple IDs/images for each popup, but make a function where the script figures out the IDs dynamically so i'm not making a separate function for each ID.
OR
2) Create the whole popup HTML markup in javascript which will allow me to dynamically populate the image source in the popup with a data-attribute. When the link is clicked, it will create the popup and the image src in the popup can be dynamically populated with a data-src from that link.
Are any of these methods in the right direction? I need to use pure JS.
http://jsfiddle.net/6sh0dogr/5/
Basic JS function from fiddle:
var popup = document.getElementById('light');
var background = document.getElementById('fade');
function popit() {
popup.style.display = 'block';
popup.style.top = parseInt(pageYOffset, 10) + 150;
background.style.display = 'block';
}
function closeit() {
popup.style.display = 'none';
background.style.display = 'none';
}
Give your divs id like this:
element.id = "image_div"+Math.round(Math.random()*10000);
Now you can select all divs with:
var nodeList = document.querySelectorAll("div[id*='image_div']");
for (var i = 0; i < nodeList.length; ++i)
{
nodeList[i].addEventListener("click", popit.bind(null, nodeList[i].id), false);
}
div[id*='image_div'] is a selector. *= means contains. So this selector selects all div elements with id that contains image_div.
Now we can attach an event handler (click) to all divs using a for loop that iterates over the nodeList. The id of the div is passed on through the bind function to the function popit.
function popit(popId) {
var node = document.getElementById(popId);
popup.style.display = 'block';
popup.style.top = parseInt(pageYOffset, 10) + 150;
background.style.display = 'block';
}
Im trying to have a href link expand/display extra text when clicked however when I click it nothing happens.
When I run the html code I can click on the link but it does not show the text for some reason.
Any idea why?
Heres the code:
<html>
click to expand
<div id="divID" style="display: none;">this is expanded</div>
</html>
I'm trying to keep the code as short as possible as the above code will have to be repeated hundreds of times for each link.
Assuming you're using jQuery, you are using the CSS selector incorrectly. Your line should be this:
click to expand
The # in #divID represents any element with an id of divID, whereas just using divID will search for divID tags (something like <divID></divID>)
See here for more documentation on the ID Selector and here's a list of all the CSS selectors you can use, including the Element Selector for you to understand why your previous code didn't work.
You can also combine CSS selectors to narrow your selection in the future, although it's not much necessary with an ID selector:
click to expand
And if you absolutely insist on not using jQuery:
click to expand
or breaking it out into its own function:
<script>
function toggleElementById(id) {
if (document.getElementById(id).style.display == 'none') {
document.getElementById(id).style.display = 'block';
} else {
document.getElementById(id).style.display = 'none';
}
}
</script>
click to expand
Add this to your page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Then:
$('#divID').toggle();
I see you're using jQuery, right? So I wrote your answer in jQuery..
$('.toggle').click(function () {
var selected = $(this).attr('href');
$('.expandable'+selected).toggle();
});
Check out the jsfiddle
If you're not using jQuery than here is the javascript version (html changed).
var expandable = document.getElementsByClassName("expandable");
for (i = 0; i < expandable.length; ++i) {
expandable[i].setAttribute('style','display: none;');
}
var toggle = document.getElementsByClassName("toggle");
for (i = 0; i < toggle.length; ++i) {
toggle[i].setAttribute('onclick','toggler(this)');
}
function toggler(obj) {
var id = obj.dataset.toggle,
el = document.getElementById(id);
el.style.display = (el.style.display != 'none' ? 'none' : '');
}
Check out the jsfiddle