Show a hidden DIV when jQuery runs (and hides another DIV) [duplicate] - javascript

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.

Related

Collapsible not Working [JSFiddle demo Included]

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

Remove class based on elements but not others

I have these sections on this side scrolling site. And want to add a class which will change styling depending if you're on a certain section.
I'm working on this function. The top is what determines the section of the side scroller you are viewing.
The let variables and below is where it stops working. I'm trying to have it so if a nonHome ID section is clicked, for example "slide-1", then add the class 'nav-visibilty'. If they are a match "slide-2" and "slide-2" then remove said class. Am I close?
https://codepen.io/mikayp-the-styleful/pen/NWPxoXR?editors=1111
setTimeout(function(){
for (i=0; i < nonHome.length; i++ ){
if (nonHome[i].id != nonHomeID){
nonHome[i].classList.add("nav-visibility");
console.log('add')
} else{
nonHomeID.classList.remove("nav-visibility");
console.log('rem')
}
}
I am still not totally clear on the behavior that you want, but there are two errors in the code that can be fixed:
It seems like you are always using 'slide-2' instead of the slideId in your event handler.
As mentioned in a comment, nonHomeID is being used incorrectly in your comparison (it is either a string or an element, but you are using it as if it was a string in the if condition, and as the element in the else branch.) Here I have kept it as an element and renamed it for clarity.
Fixing these errors results in code that applies the nav-visibility class to all slides except the one selected by the button. Is that the desired behavior?
let nonHome = document.querySelectorAll(".slide-container section");
let nonHomeSelected = document.getElementById(slideId);
var i;
setTimeout(function() {
for (i = 0; i < nonHome.length; i++) {
if (nonHome[i] != nonHomeSelected) {
nonHome[i].classList.add("nav-visibility");
console.log("add");
} else {
nonHome[i].classList.remove("nav-visibility");
console.log("rem");
}
}
}, 1000);
Edit to add: If the goal is to add nav-visibility to all only the specific slideId, you should not be adding in a loop, i.e. you need to pull your check for whether the slide is Home outside the loop. There are conceptually two steps here: remove the class from all elements that are no longer to have it, then add the class to the element that needs it.
let slideToAddVisibilityTo = document.getElementById(slideId)
let homeSlide = document.getElementById('slide-2')
let allSlides = document.querySelectorAll(".slide-container section")
for (let i = 0; i < allSlides.length; ++i)
allSlides[i].classList.remove('nav-visiblity')
if (slideToAddVisibilityTo != homeSlide)
slideToAddVisibilityTo.classList.add('nav-visibility')
Just hide them all, then show the clicked one:
function showSection(id) {
var sections = document.getElementsByTagName("section");
for(var i=0; i<sections.length; i++) sections[i].classList.remove("nav-visibility");
var current = document.getElementById(id);
current.classList.add("nav-visibility");
}
Example: showSection("foo") will remove nav-visibility from all sections, then add it to the section with id foo.

If Previous Content Div is Open, Close It and Open the Next (Plain JavaScript)

I have this simple dropdown faq system, I only want one content div to be open at a time, so I tried to use an if / else condition, but I can only make it work halfway.
I'm checking if the content div next to the trigger div has class is-visible — if not, add that class (this works)
But if the previous content div has (contains) class is-visible, I want to remove it, so only one content div is open at a time.
I've tried so many different conditions but I think I'm overcomplexifying it, this should be simple enough right?
https://jsfiddle.net/notuhm05/1/
var faqTrigger = document.querySelectorAll('.mm-faq-trigger');
for (var i = 0; i < faqTrigger.length; i++) {
faqTrigger[i].addEventListener('click', function() {
if (!this.nextElementSibling.classList.contains('is-visible')) {
this.nextElementSibling.classList.add('is-visible');
} else if (this.previousElementSibling.classList.contains('is-visible')) {
this.nextElementSibling.classList.remove('is-visible');
} else {
console.log("doesn't work");
}
});
}
Would greatly appreciate some pointers here! :-)
Here is a working solution:
Toggle the class is-visible on the clicked node
Iterate through all triggers and remove the class is-visible if the id of the href tag does not match the clicked nodes id. NOTE: I had to add an id property to the trigger href tag like <a id="1" href="#" class="mm-faq-trigger">Trigger</a>
Source Code:
var faqTrigger = document.querySelectorAll('.mm-faq-trigger');
for (var i = 0; i < faqTrigger.length; i++) {
faqTrigger[i].addEventListener('click', function() {
this.nextElementSibling.classList.toggle('is-visible');
for (var i = 0; i < faqTrigger.length; i++) {
var trigger = faqTrigger[i];
if (trigger.nextElementSibling !== null && trigger.id !== this.id) {
trigger.nextElementSibling.classList.remove('is-visible');
}
}
});
}

Javascript Custom Alert Box with Image alignment

I Have created Custom Alert Box in Javascript . I Have added text with images. but It is not align proberly. It came some thing like this.
I am trying to add the correct mark and text with same line, how can I achieve this. can anyone please help me. I have added my Custom alert box Function below.
function createCustomAlert(txt, string_url,fd) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if (d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if (d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
btn2 = alertObj.appendChild(d.createElement("img"));
btn2.id = "fd";
btn2.src = fd;
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
//btn = alertObj.appendChild(d.createElement("a"));
//btn.id = "closeBtn";
//btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
//btn.href = "";
btn = alertObj.appendChild(d.createElement("img"));
btn.id = "closeBtn";
btn.src = 'new-go-next2.png';
btn.href="#ss";
//btn.height="30px";
//btn.width="30px";
//btn.href="#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function () { removeCustomAlert(); window.location = string_url; return false; }
}
well yes creating a table would be a great approach to solve your problems , btw u can also try some internal divs with proper position anf the element having correct float attribute
Rather creating div element create table with two Columns. First of which will contain 'Image' for OK and Second one will contain your 'Text'.
Check if this helps.

Removing a div with no id or class with Javascript

My wordpress blog is having issues with syntax highlighter evolved plugin, and there's this weird div element popping out:
<div style="z-index: -1; position:absolute; top:0px; left: 0px; width: 100%; height: 4031px;"></div>
This causes my page to extend, creating a big space at the end of the page. This also is found on every wordpress blog. Funny thing is, only chrome sees that (using Inspect Element). I've already tried in IE9 developer tools and FF firebug, the div is not there and my page is fine.
NOTE: I've already posted a separate question here. And my question here is different from that.
I want to fix this little problem so bad, and it just came to my mind to use JavaScript for this. What I want to do is: Remove the div with javascript.
It's easy removing a div with an ID or class, but this one doesn't have any. I also do not want to affect all the other divs. How can I accomplish this?
P.S. It has no parent IDs or class. It's right after the container class div. It's parent is <body>.
EDIT: Here's the html:
If it's always last or close to last you can use jQuery or normal CSS3 selectors
$('body > div:last-child').remove();
OR
$('body > div:nth-last-child(n)').remove();
More on CSS3 Selectors and .remove()
OR you could use CSS i.e.
body > div:last-child (or div:nth-last-child(n)) {
display: none;
}
You could do something like this:
var els = document.getElementsByTagName('div');
for (var i = 0; l = els.length; i < l; i++) {
if (els[i].innerHTML == 'style....') {
els[i].parentNode.removeChild(els[i]);
}
}
If you are using jQuery, You can reference the div using a parent or sibling div that might have an ID or class defined.
For examample :
<div id="parentDIVID">
<div>your problem div</div>
</div>
Then you can use jQuery to reference your problem div like this : $("#parentDIVID > div")
If you can provide more html code surrounding your problem div, we can construct a jQuery selector that will work in your case.
Update : Based on the markup provided
function removeDiv() {
var parent = document.getElementById("stimuli_overlay").parentNode;
var children = document.getElementById("stimuli_overlay").parentNode.childNodes;
for (var i = 0; i < children.length; i++) {
if (children[i].style.zIndex == -1)
parent.removeChild(children[i]);
}
}
Update: Based on the fact that you can't rely on the div used below.
If the div really is the always the last div in the document, this is actually easier:
var divs, div;
divs = document.getElementsByTagName("div");
if (divs.length > 0) {
div = divs.item(divs.length - 1);
div.parentNode.removeChild(div);
}
Live example
length - 1 will remove the last div in the document. If you needed to skip a lightbox div or something, adjust to use - 2 or - 3, etc.
Old Answer using the earlier information:
Given that structure, something along these lines:
// Get the div that follows it, which conveniently has an ID
var div = document.getElementById('stimuli_overlay');
// If that worked...
if (div) {
// ...move to the previous div, with a bit of paranoia about blank non-element
// nodes in-between
div = div.previousSibling;
while (div && (div.nodeType !== 1 || div.tagName !== "DIV")) {
div = div.previousSibling;
}
// Check that this really is the right div
if (div && div.tagName === "DIV"
// The following checks look for some of the style properties that your
// screenshot shows are set on the div
&& div.style.position == "absolute"
&& div.style.zIndex == "-1"
&& div.style.top == "0px"
&& div.style.left == "0px"
&& div.style.width == "100%"
&& /* ...possibly more checks here... */) {
// Remove it
div.parentNode.removeChild(div);
}
}

Categories

Resources