Hide CSS Element Without Changing Display Property [duplicate] - javascript

This question already has answers here:
Equivalent of jQuery .hide() to set visibility: hidden
(6 answers)
Closed 4 years ago.
I would like to keep a element with initial display preserved but that is hidden (at first). I know there are other methods of hiding an element with CSS, however I also don't want the element to take up space at first. As an example
.target_element {
display: table;
}
// event happens later...
$('.loader').hide()
$('.target_element').show()
Is there a way to accomplish this? I don't want to set display to 'none' and then later come back and set it to 'table' in some JS when I want to show it.

There are several ways. Either you can make the element position: absolute or position: fixed so it doesn't take up any room and then use any of visibility: hidden, opacity: 0, etc. One thing you'd need to look out for is that if they don't have display: none, they can still receive click events, so use pointer-events: none to stop that.
My preferred combination:
#myElement {
position: absolute;
opacity: 0;
pointer-events: none;
}
And then when you want to show it:
$("#myElement").css({
'position': 'static',
'opacity': 1,
'pointer-events': 'all'
})
The bonus here is that you can transition the opacity, as opposed to visibility or display.

display:none; is definitely the way to go, unless I'm misunderstanding your question. If your issue is that .show() switches it to display:block; then just use jQuery to add a class to the element instead.
setTimeout(function() {
$('table').addClass('visible');
}, 2000);
table {
display:none;
}
table.visible {
display:table;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td></tr>
<tr><td>Test</td><td>Test</td></tr>
</table>

How long do you want to hide your element for?
There are various ways to do this, you can set a cookie in your browser or you can use a Javascript function such as setTimeout to display an element after a fixed period of time.
setTimeout( function() {
$("#your_element").show();
}, 5000); // Time in milliseconds

Use a wrapper for hiding and showing your table.
HTML
<div class="target_wrapper">
<div class="target_element"></div>
</div>
CSS
.target_element {
display: table;
}
.target_wrapper {
display: none;
}
JS
$('.target_wrapper').show()
Explanation
.show() sets display: block;. To avoid chanding the property of your table, use a wrapper, that does not depend on that property. It will be simply shown as soon as you trigger $('.target_wrapper').show() and shows up your table correctly.

// styles.css
.e.hidden {
position: 'static',
opacity: 0,
pointer-events: 'all'
}
// main.js
setTimeout(() => {
$('.e').removeClass('hidden')
}, 5000)
// index.html
<div class="e hidden">
...
</div>
How about this?

It sounds like the simplest solution would be to use visibility hidden
.target_element {
visibility: hidden;
}
Based on comments, it seems you don't want to affect your overall layout so this will make the item "invisible" but it will still take up place.

Related

Jquery this parameter for selecting child not working

I've been trying to change image source on hover, however i can use mousehover function with class name and do this. The challenge here is i'm going to dynamically call more divs with same class name so i'm trying to achieve this using the this method. for some unknown reason i couldn't execute my below code. can anyone suggest what seems to be the problem? Pasting my code below
$(".img_staff").mouseover(function() {
alert(2);
$(this).find('.staffimg:first-child').css("display","none");
$(this).find('.staffimg:nth-child(2)').css("display","block");
alert(3);
});
Both the alerts are working fine just the inbetween 2 lines are not working. i want to achieve this effect like moca tucson site's contact page
https://moca-tucson.org/contact/
I'm trying to recreate the same effect using Jquery
Apart from changing the image, the link that your provided also uses CSS transitions to bring that "image transition" effect.
Here's the similar effect with just CSS, without any javascript.
HTML:
<div>
<img src="https://moca-tucson.org/wp-content/uploads/2017/05/Ginger_Staff_Photos_001-800x800.jpg">
<img src="https://moca-tucson.org/wp-content/uploads/2017/05/Ginger_Staff_Photos_002-800x800.jpg">
</div>
CSS:
div img:last-child { opacity: 0 }
div:hover img:first-child { opacity: 0 }
div:hover img:last-child { opacity: 1 }
img {
position: absolute;
transition: 0.3s;
}

Cannot remove class from div with Javascript

I'm trying to create a class on a div and then delete it. First I thought just do like I did before with toggleClass, but that doesn't seem to work, because I'm adding a class to an ID instead of a Class. I want my header to have a black background top as well with the class: headerbg.
Also I have a small question about the color of my hamburger menu. I wanted to have a toggle for colors of the white lines (orange instead of white) on the class when pressed on the hamburger menu.
My live version where it is on, works only when 1024px or smaller
My Javascript
$(document).ready(function(){
$(".hamburger").click(function(){
$(".hamburger").toggleClass("closed");
$(".menu").toggleClass("show");
$("header").addClass('headerbg');
});
});
My CSS
.hamburger div{
height: 3px;
background-color: white;
margin: 5px 0;
border-radius: 25px;
transition: 0.3s;
}
.hamburger {
width: 30px;
display: none;
margin: 3em 3em 3em 0;
float: right;
transition: all 0.75s 0.25s;
}
.one {
width: 30px;
}
.two {
width: 20px;
}
.three {
width: 25px;
}
.hamburger:hover div {
width: 30px;
}
.hamburger.closed {
-webkit-transform: rotate(45deg);
-moz-transform: rotate(45deg);
}
#media only screen and (max-width: 1024px) {
.menu {
width: 100%;
background: #000;
margin: 0;
display: none;
}
.show {
width: 100%;
background: #000;
margin: 0;
display: block;
}
.headerbg {
background: #000;
}
.hamburger {
display: block;
}
}
If anyone maybe could lead me to a good example or even better help me out I would really appreciate it! Just came back after 2,5 years break from HTML/CSS as well.
Thanks for looking at the question!
Your understanding of DOM elements seems to be vague. Let's break it down.
I'm trying to create a class on a div and then delete it.
What is it here, what are you trying to delete? The class or the element?
..., because I'm adding a class to an ID instead of a Class.
That's not technically possible. You can't add a class to an id, nor can you add an id to a class. You can only add/remove/modify the id attribute of a DOM element and you can add/remove classes to the className property of a DOM element, referenced in markup by the class attribute.
To keep it short, using jQuery, you can select one or multiple elements by ID, by class, by attribute or by attribute value (in fact, by any valid CSS selector that matches the element), and you can apply the .toggleClass(), .addClass() or .removeClass() methods (or any other jQuery methods) to that element (or to each element in the collection, if they are more than one).
To clarify things for you here's what your current code does:
$(document).ready(function(){
/* when all the DOM has finished building... */
$(".hamburger").click(function(){
/* do the following when an element with class "hamburger" is clicked: */
$(".hamburger").toggleClass("closed");
/* toggle class `closed` on all elements with class "hamburger"
(not only on clicked one!) */
$(".menu").toggleClass("show");
// toggle class `show` on all elements with class "menu"
$("header").addClass('headerbg');
// add class "headerbg" to all <header> elements in page
});
});
Addition, as per OP comment:
First I want to add the class .headerbg on the <header> when I click on the .hamburger class, then when I click on the .hamburger class again I want to delete/remove the class .headerbg for the <header>
This will do it:
/*
* place the following inside an instance of
* $(document).ready(function(){...})
*/
$('.hamburger').on('click', function(){
$('header').toggleClass('headerbg');
})
Note:
$(selector).click(function(){...}) is a shortcut for
$(selector).on('click', [child-selector,] function(){...}). I personally recommend using the latter for all event binding functions to develop a consistent pattern of binding. It helps in the long run, when maintaining code. Also, it allows binding on elements that are not yet in DOM, by using the optional child selector argument. For example, if you wanted to do the binding before .hamburger was created in DOM, you could have, with the following syntax:
$(window).on('click', '.hamburger', function(){
$('header').toggleClass('headerbg');
})
The main difference is the first syntax binds an event listener on each and every instance of .hamburger it finds at the time the binding is done (document.ready in your case).
The second syntax binds only one event, on window object and evaluates at the moment of click if it was fired from inside an element with class .hamburger or not. This means that if you have 1k elements with class .hamburger, you don't bind an event on each of them (resulting in 1k listeners). Also, it has the great advantage that it will work on elements that are added to the page after the binding is done (because evaluation is done at the click event, not at the ready event.
To be even more precise and clear, there are two syntax choices here.
1. Choose between:
.click(function(){...})
.on('click', function(){...})
I always go for second, because it's consistent across all event listeners (it doesn't matter what I put as first argument, instead of click - also, it allows to bind on more than one event type at once: .on('click tap swipe', function(){...}))
2. Choose between
$(child-selector).on('click', function(){...})
$(parent-selector).on('click', child-selector, function(){...}).
If there is only one instance of child-selector and it's already in DOM at the time you do the binding, choose first. If there are more than one instances of child-selector and you want each one present inside parent-selector, use second.
Theoretically speaking, you want as few event listeners as possible, so instead of 2 listeners, one on each child is better to have a single listener on a parent.
Also, best practice is to use the smallest parent selector possible. For example, if you know all your child-selectors will always be contained in a div holding your content — say $('#main') — it's best to bind on that container rather than on $('<body>') or $(window). This will make your code not be evaluated against a click event triggered outside of $('#main'), which in both theory and practice makes your page faster and lighter, for a better user experience.
in your #header you should toggle the headerbg not just adding it :
then your jquery must be :
$(document).ready(function(){
$(".hamburger").click(function(){
$(".hamburger").toggleClass("closed");
$(".menu").toggleClass("show");
if($("#header").hasClass("headerbg")){
$("#header").removeClass("headerbg");
}
else
{
$("#header").addClass("headerbg");
}
});
});
if you need to add the styles of the ID you should pass it through the attr function . like this
$(document).ready(function(){
$(".hamburger").click(function(){
$(".hamburger").toggleClass("closed");
$(".menu").toggleClass("show");
$("header").addClass('headerbg');
$("header").attr('id','#header');
});
});
and you can delete it like this
$("header").attr('id','');
this way you can toggle it

how to show hover effect on a image where i hover my mouse

i have multiple images, on hover on particular image i want to apply on that image only, it should not effect on other image.
More Explanation:
In this example(http://codepen.io/anon/pen/AnsqI), suppose i have multiple images & want to apply the certain effect on only on that image where i hove my mouse.
I am using class attribute...
<script>
$(function() {
//For grid view hover effect
$('.grid_content').hide()
$('.grid_container').hover(
// Over
function() {
$('.grid_content').fadeIn();
}
,
// Out
function() {
$('.grid_content').fadeOut();
}
);
//--js for grid view hover effect ends here
});
</script>
Something i have to apply like $this , i tried like($this.$('.grid_content').fadeOut();)but it did not work.
Somebody please help me.
Use this:
$('.container').hover(function(){
$('.content',this).fadeToggle();
});
Check this Demo http://codepen.io/anon/pen/BxbID
You could consider using CSS and the opacity attribute (or display). You could progressively enhance the hover effect with CSS3's transition property as well. There isn't necessarily a need for JS here, and I only added five lines of CSS (unprefixed) to achieve the same effect.
.content {
width: 100%;
height: 100%;
background: rgb(255,255,255,0.9);
padding: 5px 15px 10px 15px;
box-sizing: border-box;
opacity: 0;
transition: opacity .2s linear; /* CSS3 progressive enhancement */
}
.content:hover {
opacity: 1;
}
Depending on how you organize your HTML, you may need to make modifications, but the concept is the same.
Check out the demo: http://jsfiddle.net/NeEuP/1/
There are 2 ways to do this. You can either reference it using the this javascript keyword and surrounding it in a jQuery function:
$('.grid_container').hover(function(){
$(this).fadeIn();
, function(){
$(this).fadeOut();
});
Or you can:
$('.grid_container').hover(function(e){
$(e.currentTarget).fadeIn();
, function(e){
$(e.currentTarget)$(this).fadeOut();
});
... basically you're getting element through the event object. I personally prefer this method, because it's more flexible it doesn't depend on the actual scope (this depends on scope).

Changing Visibility of HTML elements

I want to change the visibility of HTML elements except some particular elements. I want the elements to be at the same positions and alignments and just the visibility of elements to be changed. Can somebody please help me doing that?
I tried doing the same using jquery by seeing the answer to How to hide all elements except one using jquery? but this changes the positions and alignments of elements.
$('body > :not(#averageCustomerReviews)').hide(); //this hid everything
$('#averageCustomerReviews').appendTo('body'); //but this changed the position
I currently have locators to elements like xpaths/CSS Selectors which I don't want to hide.
For e.g. I have this link. And I want to view only at the place it is right now by hiding all other elements.
VISIBILITY USAGE
jQuery
$("#element").css("visibility", "hidden");
CSS
#element {
visibility: hidden;
}
If you want all the others elements than #element to be "invisible":
jQuery
$(":not(#element)").css("visibility", "hidden");
CSS
:not(#element) {
visibility: hidden;
}
ANSWERING YOUR 'AFTER' QUESTION - LET ALL INVISIBLE EXCEPT ONE
If you can't assign an 'invisible' class to the elements that should be invisibile (best solution), you can render visible only one child element in this manner, see JsFiddle.
That mean:
set all 'invisible': $("*").css("visibility", "hidden");
set visible the element you want to show: $("#element").css("visibility", "visible");
In your case the element you would like to show is a little 'nested' and you can do in this manner:
// set all 'invisible'
$("*").css("visibility", "hidden");
// set visible the element with their 'sub-child'
$("#averageCustomerReviews_feature_div, #averageCustomerReviews, #averageCustomerReviews a, .reviewCountTextLinkedHistogram, .reviewCountTextLinkedHistogram a, .a-popover-trigger, .a-popover-trigger i").css("visibility", "visible");
Not nice, but it works.
With a html tree complex like this one and without any possibility to assign some custom class. I think that this is the only solution...
Use visibility: hidden;. Unlike display: none; the element will still be there.
Too apply to all elements except one use a style like this:
* {
visibility: hidden;
}
#element {
visibility:visible !important;
}
JSFiddle
Information on visibility.
If you are looking to hide everything but #element then use this:
:not(#element) {
visibility: hidden;
}
See here for more info on the :not() selector: https://developer.mozilla.org/en-US/docs/Web/CSS/:not
UPDATE
You can also chain :not() selectors together to exclude multiple elements. For example, if you have #element1 and #element2 that should not be hidden from view, then do something like this:
:not(#element1):not(#element2) {
visibility: hidden;
}
You can set up in CSS, where class is the class that's on all the elements you want to hide:
.class {
visibility: hidden;
}
and then
$('#element').css('visibility', 'visible');
use this
jquery
$("#elementid").onclick(function() {
$('body').css({ 'visibility': 'hidden'});
$('#elementid').css({ 'visibility': 'visible'});
});

I am trying to arrange my html/css/jquery so I can toggle the visibility of a div by double clicking on it

I am trying to arrange my html/css/jquery so I can toggle the visibility of a
div by double clicking on it. I can make it hidden by a double click but when I
double click again it does not reappear. When I check to see all of the div outlines,
the outline of this div is no longer there. I use a web developer plugin to check.
I am using the following codes to try to accomplish this:
My css classes are..
.hidden { visibility: hidden; }
.unhidden { visibility: visible; }
the html is...
<div id="ConstructionDiv" ondblclick="unhide('ConstructionDiv')" class="unhidden">
<!.. the div is unhidden at page load. When I look at generated
source code after the double click the class is "hidden"
-->
</div>
my javascript is...
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
Is it possible to do what I am trying? There must be something that works.
Thank you.
I just tried this, and invisible elements cannot receive click events.
As Andy said, Opacity 0 can receive click events just fine, and the contents are still invisible.
Use the following css rules:
.hidden {
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=1)";
filter: alpha(opacity=1);
-moz-opacity:.1;
-khtml-opacity: .1;
opacity: .1;
}
.unhidden {
-ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)";
filter: alpha(opacity=100);
-moz-opacity:1;
-khtml-opacity: 1;
opacity: 1;
}
UPDATE
You can also wrap the element in some other element like div and then use the click of that div to show or hide the inner content.
What if you have two divs, both placed absolutely, but one possibly much larger than the other. clicking one changes the visibility of both of them.

Categories