how can I alter my code to hide element on load? - javascript

I'm using this js code to show/hide elements on my site:
<script>
function myFunction3() {
var x = document.getElementById("dsec-three");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
</script>
Can anyone help me to set it so the elements are hidden on load and only show once activated?

you can use class for show/hide elements same as :
function showHide(){
element = document.getElementById('element1');
showHideEle(element)
}
function showHideMulti(){
elements = document.getElementsByClassName('multi');
Array.from(elements).forEach(ele => {
showHideEle(ele)
});
}
function showHideEle(ele){
let isHide = ele.classList.contains('hide');
if (isHide) {
ele.classList.remove("hide");
} else {
ele.classList.add("hide");
}
}
.hide {
display: none
}
<p class="hide" id="element1">para 1</p>
<button onclick="showHide()">Show/Hide</button>
<br />
<p class="hide multi">para 2</p>
<p class="hide multi">para 3</p>
<p class="hide multi">para 4</p>
<button onclick="showHideMulti()">Show/Hide Multi</button>

Your function myFunction3 already does the job of hiding and showing the relevant elements. All you need to do now is invoke the function when your document loads. You can do this by adding the following line inside your <script>:
document.addEventListener("load", myFunction3);
If you need the elements to stay hidden by default and show them after the document loads, you'll need to set the display property of those elements to none either via inline CSS.
Example (if your element is a div) :
<div id="dsec-three" style="display:none">
...
</div>

what do you mean by activated?
if you mean that after the load of your page, you would need an event listener.
follow these steps:
set the initial display of your element to none.
create an event listener like load: and add your function there:
document.addEventListerer('load', function(){
myFunction3();
})
the above code is telling the browser: 'when ever the page loads, call this function'

Related

How to show hidden div onclick of button and hide when not in focus using JS

I'm trying to create add a way to show a div onclick of a button and hide it when not in focus / when user clicks outside the div.
I've already managed to add a button that can show a hidden div, but I can't figure out how to make it hidden again when focus is lost.
I've read this: Hide a DIV when it loses focus/blur
...and other articles, but I couldn't follow them to make it work..
Please see my code so far:
function openCardsList() {
let window = document.getElementById("anchor-cards-list");
window.style.display = "block";
}
$(document).not("#anchor-cards-list").click(function() {
$('#anchor-cards-list').hide();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<div class="collapse" id="anchor-cards-list">Lorem Ipsum</div>
<button id="anchor-open-cards-list-btn" onclick="openCardsList();">Collapse Maincard</button>
Any help would be appreciated. Thank you in advance!
you can use this code :
function openCardsList() {
let window = document.getElementById("anchor-cards-list");
window.style.display = "block";
}
function hideDiv(){
let window = document.getElementById("anchor-cards-list");
window.style.display = "none";
}
and add onclick event to parent div
div onclick="hideDiv()" style="height: 100vh;">
<div class="collapse" id="anchor-cards-list">Lorem Ipsum</div>
</div>
I'd personally simplify things to separate concerns. Add an event listener to the button (click) to show your div, and an event listener (blur) on the div to hide it again.
document.getElementById('anchor-open-cards-list-btn').addEventListener('click', showDiv);
document.getElementById('anchor-cards-list').addEventListener('blur', hideDiv);
Then showDiv and hideDiv just handle the element visibility.
Use jquery simple way
use toggle() instead of show/hide, because it is more clear and simple.
$(document).ready(function(){
$("#anchor-open-cards-list-btn").click(function(){
$("#anchor-cards-list").toggle();
});
});
OR
function openCardsList() {
$("#anchor-cards-list").toggle();
}
OR
For onblue you can also use this code
function openCardsList() {
$("#anchor-cards-list").css('display','block');
}
function hideD(){
$("#anchor-cards-list").css('display','none');
}
add onclick event in parent div
div onclick="hideD()">
<div id="anchor-cards-list">text</div>
</div>
i prefer to make let window outside the function so you can use it anytime needed. and also if you only make this for handle show/hide div while onclick and onblur you dont need jquery. the default javascript can deliver those event action.
script.js
let card = document.getElementById('anchor-cards-list')
function openCard() {
card.style.display = 'block'
}
function blurCard() {
card.style.display = 'none'
}
index.html
<div id="anchor-cards-list">Hello Text</div>
<button onclick="openCard()" onblur="blurCard()">Clik me</button>

Toggle re-hides all divs; need parent div to remain visible

Apologies in advance, I'm not terribly familiar with Javascript, but I do understand what this code is doing and why it is causing me this problem. I'm just not sure how to go about solving it AT all.
On my webpage I have an open/close dialogue toggle which is the parent div, the dialogue box is hidden upon the page loading. Within this dialogue box are more hidden divs for the dialogue options. Problem is, when one of the dialogue options is clicked, the script hides the entire dialogue box, preventing any of the dialogue options from being seen, because it can only show one div at a time, regardless of its parent or child status. When a div is clicked, all other divs are re-hidden.
I need the parent div to remain visible until the dialogue box toggle is clicked again. The individual choices DO need to hide/unhide when another choice is clicked.
Not sure if I should include any CSS here, it's just styling the dialogue box and its buttons within.
<div id="dialogue" style="display:none;">
<div class="room">
Room description here. What do you do?
<div class="buttons">
Pet the cat.
<br>
<div id="cat" style="display:none;">aw yeah kitty time</div>
Turn on the radio.
<br>
<div id="radio" style="display:none;">
<br>
audio file and tracklist here
</div>
</div>
</div>
</div>
<span class="toggle">
[Open/close dialogue.]
</span>
<script type="text/javascript">
var divs = ["cat", "radio", "dialogue"];
var visibleDivId = null;
function divVisibility(divId) {
if(visibleDivId === divId) {
visibleDivId = null;
} else {
visibleDivId = divId;
}
hideNonVisibleDivs();
}
function hideNonVisibleDivs() {
var i, divId, div;
for(i = 0; i < divs.length; i++) {
divId = divs[i];
div = document.getElementById(divId);
if(visibleDivId === divId) {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
}
</script>
I probably need a third function here because currently all the toggles are grouped together, hence why they're interacting like this, but I don't have the first clue how to accomplish this. I have been looking and haven't found anything that seems to match my needs.
Made a few corrections to your HTML so the href does not refresh the page on click. Also added in a few attributes (aria-controls) to track which div the button controls. I added comments to the JavaScript. There are plenty of Aria attributes they typically help with accessibility but they are super useful for keeping track of things in HTML and passing information to JavaScript.
//create a function to handle the click that takes in the event as a argument
function handleClick(event) {
//find out which div the button controls
const ariaControls = event.currentTarget.getAttribute("aria-controls"),
//select the controlled div
controlledAria = document.getElementById(ariaControls);
// if the controlled div is cat
if (ariaControls === "cat") {
// hide the radio div
document.getElementById("radio").classList.add("hide");
// if the controlled div is radio
} else if (ariaControls === "radio") {
// hide the car div
document.getElementById("cat").classList.add("hide");
}
//toggle the hide div on the controlled div
controlledAria.classList.toggle("hide");
}
//select all the buttons
const buttons = document.querySelectorAll("button");
//for each button add an event listener when the button is clicked run the handle click function
buttons.forEach(button => button.addEventListener("click", handleClick))
.hide {
display: none;
}
<div id="dialogue" class="hide">
<div class="room">
Room description here. What do you do?
<div class="buttons">
<button aria-controls="cat">Pet the cat.</button><br>
<div id="cat" class="hide">aw yeah kitty time</div>
<button aria-controls="radio">Turn on the radio.</button><br>
<div id="radio" class="hide">audio file and tracklist here
</div>
</div>
</div>
</div>
<span class="toggle"><button aria-controls="dialogue">[Open/close dialogue.]</button></span>

hide / show div with a button not in the same div

I'm using elementor for my wordpress site and I wish to have a button in a first div (section) that control if a second and separate div (section) is display or not. I've tried to use the checkbox hack but it's working only if the checkbox is in the div as the content https://css-tricks.com/the-checkbox-hack/
Is there a solution to use CSS or even javascript ? If you advice to me to use javascript I'll put in my function.php file and as I'm begginer in javascript can you please write all the function I have to implement into my function.php file.
Basically it means :
<div>button</div> <div>content to show and hide on click on the button</div>
Best regards,
Clément
You can use Jquery:
1-Put an id to your DIV
<div id = "btn_show"> button </div> <div id = "show"> content to show and hide on click on the button </div>
2-Call jquery to display it
$("#btn_show").click(function(){
$("#show").show();
//or
$("#show").hide();
});
And jquery you can call it with CDN
<script src="https://code.jquery.com/jquery-3.6.0.js"</script>
In javascript without any library this could be very easy but you need to put an id on your divand your button.
<div id="myButton">button</div>
<div id="myDiv">
content to show and hide on click on the button
</div>
Then you just add a script section like this : (it just need to be after your div and your button in the DOM)
<script>
var myDiv = document.getElementById('myDiv');
var myButton = document.getElementById('myButton');
myButton.addEventListener('click', e => {
myDiv.classList.toggle('visible'):
});
</script>
And at last, you need a css like this:
.visible {
display: none;
}
Thanks for all of yours answers! Here what I use:
<button onclick="myFunctionopenclose()">Click Me</button>
<div id="myDiv" style="display:none;">content to hide and show</div>
<script> function myFunctionopenclose() {
var x = document.getElementById("myDiv");
if (x.style.display === "block") {
x.style.display = "none"; }
else {
x.style.display = "block";}}
Best regards,
Clément

If div in iframe has child with specific class do

I want to add a class to the parent if the child has a specific class.
The problem: It's in an iFrame and I'm not very good with jQuery. It don't really has to be jQuery, any other way would be also great. Just notice: The iFrame is on my domain, but I can't access it, because it's generated by a plugin.
If you have any ideas how to fix it, I would appreciate it
My HTML looks somewhat like this in devtools:
<iframe src="#" id="iFrameResizer0">
<div class="book-day">
<button class="disabled">Button Text</button>
</div>
<div class="book-day">
<button class="active">Button Text</button>
</div>
</iframe>
and my jQuery:
$(document).ready(function () {
$("#iFrameResizer0").contents().find(".book-day button")
if ($('.book-day button').hasClass('disabled')) {
$(".book-day button").parent().addClass('disabled');
}
});
if everything works correct I want my html looks like this afterwards:
<iframe src="#" id="iFrameResizer0">
<div class="book-day disabled">
<button class="disabled">Button Text</button>
</div>
<div class="book-day">
<button class="active">Button Text</button>
</div>
</iframe>
Devtools:
NOTE: this code has to be executed AFTER the iFrame has loaded and rendered. If you execute this in the head of the parent page without wrapping it in $(function() { ... }), it will not work
You have more than one book-day, you will need to loop:
$("#iFrameResizer0").contents().find(".book-day button").each(function() {
$(this).parent().toggleClass('disabled',$(this).is('.disabled'));
})
or perhaps
$("#iFrameResizer0").contents().find(".book-day button.disabled").each(function() {
$(this).parent().addClass('disabled');
})
PS: To remove them you do not need to give them a class:
$("#iFrameResizer0").contents().find(".book-day button.disabled").each(function() {
$(this).parent().remove;
})
If you still have issue with the timing, try this script right after the iframe tags - right after the </iframe>
<script>
$("#iFrameResizer0").on("load",function() {
$("#iFrameResizer0").contents().find(".book-day button.disabled").each(function() {
$(this).parent().remove(); // or .addClass('disabled');
})
})
</script>
UPDATE: Alternatively drop the iFrame completely:
Replace the iframe tags with <div id="iFrameResizer0"></div>
and add
<script>
$("#iFrameResizer0").load("/wp-json/ssa/v1/embed-inner?integration.../type/Reservierung",function() {
$("#iFrameResizer0").find(".book-day button.disabled").each(function() {
$(this).parent().remove(); // or .addClass('disabled');
});
});
</script>
Example pretending your iframe.content() works as expected (same origin)
$(function() { // on page load. This might STILL be too early
$("#iFrameResizer0").contents().find(".book-day button.disabled").each(function() {
$(this).parent().addClass('disabled');
})
});
.disabled {
background-color: grey
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="iFrameResizer0">
<div class="book-day disabled">
<button class="disabled">Button Text</button>
</div>
<div class="book-day">
<button class="active">Button Text</button>
</div>
<div class="book-day disabled">
<button class="disabled">Button Text</button>
</div>
</div>
You don't have to check for every button if it has disabled class or not. You can directly select those button having disabled class.
In Javascript, you have to iterate for all the buttons having disabled class, and add disabled class to it's parent. However, in jQuery, as you can see, you can achieve that, without using any loop.
For JavaScript :
$(document).ready(function() {
var all = document.querySelectorAll('#iFrameResizer0 .book-day button.disabled');
all.forEach((item) => {
item.parentElement.classList.add('disabled');
})
});
For jQuery :
$("#iFrameResizer0 .book-day button.disabled").parent().addClass('disabled');
Since the iframe is observing same-origin policy, This is possible.
First you need to select your iframe element using the following JS
var iframe = document.getElementById('iFrameResizer0');
Now you need to get the content in your iframe
var iframeContent = iframe.contentDocument;
Then select elements inside your Iframe which you wish to modify
var iframeElement = iframeContent.getElementsByClassName("book-day");
var i = 0, ilen = iframeElement.length - 1;
for (var i = 0; i < ilen; i++) {
var button = iframeElement.getElementsByTagName("button");
if(button.className == 'disabled')
{
iframeElement[i].className == 'disabled';
}
}
Then hide your element using CSS display:none property
.disabled {display:none;}

Show div onclick not working (Javascript)

Javascript newbie here. Anyone could let me know what is wrong with my code? The div-to-show does not show after click and I can't figure out why...
let div = document.getElementById('div-to-show');
function openDiv() {
if (div.style.display === 'none') {
div.style.display = 'block';
}
}
#div-to-show {
display: none;
}
<p onclick="openDiv">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
There are 2 problems here.
First, you aren't invoking the function with onclick="openDiv" - you have to put () after a function name to invoke it, eg onclick="openDiv()".
Secondly, although you have a CSS rule of display: none, that doesn't result in the CSS property on the element itself changing; it remains the empty string:
let div = document.getElementById('div-to-show');
function openDiv() {
console.log(div.style.display);
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
Instead, to check whether the element is being displayed, you can check whether its offsetParent is null:
let div = document.getElementById('div-to-show');
function openDiv() {
div.style.display = div.offsetParent === null ? 'block' : 'none';
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
For the general case of checking what CSS rules are being applied to a particular element, you can use getComputedStyle:
let div = document.getElementById('div-to-show');
const styleProp = div.style;
const styleDec = window.getComputedStyle(div);
function openDiv() {
styleProp.display = styleDec.display === 'none' ? 'block' : 'none';
}
#div-to-show {
display: none;
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
<!DOCTYPE html>
<html>
<head>
<style>
#div-to-show{
display: none;
}
</style>
</head>
<body>
<p onclick="openDiv()">Clique</p>
<div id="div-to-show">
<p>I am visible</p>
</div>
<script type="text/javascript">
let div = document.getElementById('div-to-show');
function openDiv(){
if(window.getComputedStyle(div).display === 'none'){
div.style.display = 'block';
}
}
</script>
</body>
</html>
In your code is wrong the way you write onclick in this tag <p>, you need to write onclick in this way:
<p onclick="openDiv()">Clique</p>
and try again.
You should mention function name correctly on onclick. onclick=openDiv should be replaced to onclick=openDiv().
You should define the display css style directly on the tag to get div.style.display on javascript. document.getElementById('...').style will only contain the style attributes which are defined on html tag style attribute only so to compare, it will be needed to set display attribute on html file directly.
let div = document.getElementById('div-to-show');
function openDiv() {
if (div.style.display === 'none') {
div.style.display = 'block';
}
}
<p onclick="openDiv()">Clique</p>
<div id="div-to-show" style="display: none;">
<p>I am visible</p>
</div>
Hi as some other examples here explains, you should use the addEvenlListener. If you only what to show the div on the click event you do not need a if statement. You can add a class to the div that sets the display:none. Then in the code you only need to call the remove on the classList on the div. This will not throw an error or do anything if the class is not in the classList. So no need to implement any check logic.
Using the hidden class makes so you do not need to know what the display value was on the div element initially. Less to worry about.
https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/remove
let div = document.getElementById('div-to-show')
document.getElementById('p-button').addEventListener("click", openDiv);
function openDiv() {
div.classList.remove('hidden');
}
#div-to-show.hidden {
display: none;
}
<p id="p-button">Clique</p>
<div id="div-to-show" class="hidden">
<p>I am visible</p>
</div>

Categories