How to disable all div content - javascript

I was under the assumption that if I disabled a div, all content got disabled too.
However, the content is grayed but I can still interact with it.
Is there a way to do that? (disable a div and get all content disabled also)

Many of the above answers only work on form elements. A simple way to disable any DIV including its contents is to just disable mouse interaction. For example:
$("#mydiv").addClass("disabledbutton");
CSS
.disabledbutton {
pointer-events: none;
opacity: 0.4;
}
Supplement:
Many commented like these: "This will only disallow mouse events, but the control is still enabled" and "you can still navigate by keyboard". You Could add this code to your script and inputs can't be reached in other ways like keyboard tab. You could change this code to fit your needs.
$([Parent Container]).find('input').each(function () {
$(this).attr('disabled', 'disabled');
});

Use a framework like JQuery to do things like:
function toggleStatus() {
if ($('#toggleElement').is(':checked')) {
$('#idOfTheDIV :input').attr('disabled', true);
} else {
$('#idOfTheDIV :input').removeAttr('disabled');
}
}
Disable And Enable Input Elements In A Div Block Using jQuery should help you!
As of jQuery 1.6, you should use .prop instead of .attr for disabling.

Here is a quick comment for people who don't need a div but just a blockelement. In HTML5 <fieldset disabled="disabled"></fieldset> got the disabled attribute. Every form element in a disabled fieldset is disabled.

I just wanted to mention this extension method for enabling and disabling elements. I think it's a much cleaner way than adding and removing attributes directly.
Then you simply do:
$("div *").disable();

You can use this simple CSS statement to disable events
#my-div {
pointer-events:none;
}

The disabled attribute is not part of the W3C spec for DIV elements, only for form elements.
The jQuery approach suggested by Martin is the only foolproof way you're going to accomplish this.

Wrap the div within the form and fieldset tags:
<form>
<fieldset disabled>
<div>your controls</div>
</fieldset>
</form>

similar to cletu's solution, but i got an error using that solution, this is the workaround:
$('div *').prop('disabled',true);
// or
$('#the_div_id *').prop('disabled',true);
works fine on me

If you wanted to keep the semantics of disabled as follows
<div disabled="disabled"> Your content here </div>
you could add the following CSS
div[disabled=disabled] {
pointer-events: none;
opacity: 0.4;
}
the benefit here is that you're not working with classes on the div that you want to work with

One way to achieve this is by adding the disabled prop to all children of the div. You can achieve this very easily:
$("#myDiv").find("*").prop('disabled', true);
$("#myDiv") finds the div, .find("*") gets you all child nodes in all levels and .prop('disabled', true) disables each one.
This way all content is disabled and you can't click them, tab to them, scroll them, etc. Also, you don't need to add any css classes.

As many answers already clarified disabled is not a DIV attribute. However xHTML means Extensible HTML. It means you can define your own HTML attributes (all Frontend frameworks does that as well). And CSS supports attribute selectors which is [].
Use standard HTML with your defined attribute:
<div disabled>My disabled div</div>
Use CSS:
div[disabled] {
opacity: 0.6;
pointer-events: none;
}
NOTE: you can use CSS attribute selector with ID or Class names as well e.g. .myDiv[disabled] {...} Also can apply value filter e.g.: following HTML disabling standard attribute with value div[disabled=disabled] {...}.

Browsers tested: IE 9, Chrome, Firefox and jquery-1.7.1.min.js
$(document).ready(function () {
$('#chkDisableEnableElements').change(function () {
if ($('#chkDisableEnableElements').is(':checked')) {
enableElements($('#divDifferentElements').children());
}
else {
disableElements($('#divDifferentElements').children());
}
});
});
function disableElements(el) {
for (var i = 0; i < el.length; i++) {
el[i].disabled = true;
disableElements(el[i].children);
}
}
function enableElements(el) {
for (var i = 0; i < el.length; i++) {
el[i].disabled = false;
enableElements(el[i].children);
}
}

HTML input controls can be disabled using 'disabled' attribute as you know. Once 'disabled' attribute for an input control is set, event handlers associated with such control are not invoked.
You have to simulate above behavior for HTML elements that don't support 'disabled' attribute like div, if you wish.
If you have a div, and you want to support click or a key event on that div, then you have to do two things:
1) When you want to disable the div, set its disabled attribute as usual (just to comply with the convention)
2) In your div's click and/or key handlers, check if disabled attribute is set on the div. If it is, then just disregard the click or key event (e.g. just return immediately). If disabled attribute is not set, then do your div's click and/or key event logic.
Above steps are browser independent as well.

How to disable the contents of a <div/>
The CSS pointer-events property alone doesn't disable child elements from scrolling, and it's not supported by IE10 and under for <div/> elements (only for SVG).
http://caniuse.com/#feat=pointer-events
To disable the contents of a <div/> on all browsers.
Jquery:
$("#myDiv")
.addClass("disable")
.click(function () {
return false;
});
CSS:
.disable {
opacity: 0.4;
}
/* Disable scrolling on child elements */
.disable div,
.disable textarea {
overflow: hidden;
}
To disable the contents of a <div/> on all browsers, except IE10 and under.
Jquery:
$("#myDiv").addClass("disable");
CSS:
.disable {
/* Note: pointer-events not supported by IE10 and under */
pointer-events: none;
opacity: 0.4;
}
/* Disable scrolling on child elements */
.disable div,
.disable textarea {
overflow: hidden;
}

This is for the searchers,
The best I did is,
$('#myDiv *').attr("disabled", true);
$('#myDiv *').fadeTo('slow', .6);

As mentioned in comments, you are still able to access element by navigating between elements by using tab key. so I recommend this :
$("#mydiv")
.css({"pointer-events" : "none" , "opacity" : "0.4"})
.attr("tabindex" , "-1");

Or just use css and a "disabled" class.
Note: don't use the disabled attribute.
No need to mess with jQuery on/off.
This is much easier and works cross browser:
.disabled{
position: relative;
}
.disabled:after{
content: "";
position: absolute;
width: 100%;
height: inherit;
background-color: rgba(0,0,0,0.1);
top: 0;
left: 0;
right: 0;
bottom: 0;
}
Then you can shut it on and off when initializing your page, or toggling a button
if(myDiv !== "can be edited"){
$('div').removeClass('disabled');
} else{
$('div').addClass('disabled');
}

I thought I'd chip in a couple of notes.
< div > can be disabled in IE8/9. I assume this is "incorrect", and it threw me off
Don't use .removeProp(), as it has a permanent effect on the element. Use .prop("disabled", false) instead
$("#myDiv").filter("input,textarea,select,button").prop("disabled", true) is more explicit and will catch some form elements you would miss with :input

I would use an improved version of Cletus' function:
$.fn.disable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined") {
$(this).data('jquery.disabled', this.disabled);
this.disabled = true;
}
});
};
$.fn.enable = function() {
return this.each(function() {
if (typeof this.disabled != "undefined") {
this.disabled = $(this).data('jquery.disabled');
}
});
};
Which stores the original 'disabled' property of the element.
$('#myDiv *').disable();

Below is a more comprehensive solution to masking divs enabling
no separate CSS
cover the whole page or just an element
specify mask color and opacity
specify Z-index so you can show popups over the mask
show an hourglass cursor over the mask
removing the masking div on maksOff so a different one can be shown later
stretch mask when element resize
return the mask element so you can style it etc
Also included is hourglassOn and hourglassOff which can be used separately
// elemOrId - jquery element or element id, defaults to $('<body>')'
// settings.color defaults to 'transparent'
// settings.opacity defaults to 1
// settings.zIndex defaults to 2147483647
// if settings.hourglasss==true change cursor to hourglass over mask
function maskOn(elemOrId, settings) {
var elem=elemFromParam(elemOrId);
if (!elem) return;
var maskDiv=elem.data('maskDiv');
if (!maskDiv) {
maskDiv=$('<div style="position:fixed;display:inline"></div>');
$('body').append(maskDiv);
elem.data('maskDiv', maskDiv);
}
if (typeof settings==='undefined' || settings===null) settings={};
if (typeof settings.color==='undefined' || settings.color===null) settings.color='transparent';
if (typeof settings.opacity==='undefined' || settings.opacity===null) settings.opacity=1;
if (typeof settings.zIndex==='undefined' || settings.zIndex===null) settings.zIndex=2147483647;
if (typeof settings.hourglass==='undefined' || settings.hourglass===null) settings.hourglass=false;
// stretch maskdiv over elem
var offsetParent = elem.offsetParent();
var widthPercents=elem.outerWidth()*100/offsetParent.outerWidth()+'%';
var heightPercents=elem.outerHeight()*100/offsetParent.outerHeight()+'%';
maskDiv.width(widthPercents);
maskDiv.height(heightPercents);
maskDiv.offset($(elem).offset());
// set styles
maskDiv[0].style.backgroundColor = settings.color;
maskDiv[0].style.opacity = settings.opacity;
maskDiv[0].style.zIndex = settings.zIndex;
if (settings.hourglass) hourglassOn(maskDiv);
return maskDiv;
}
// elemOrId - jquery element or element id, defaults to $('<body>')'
function maskOff(elemOrId) {
var elem=elemFromParam(elemOrId);
if (!elem) return;
var maskDiv=elem.data('maskDiv');
if (!maskDiv) {
console.log('maskOff no mask !');
return;
}
elem.removeData('maskDiv');
maskDiv.remove();
}
// elemOrId - jquery element or element id, defaults to $('<body>')'
// if decendents is true also shows hourglass over decendents of elemOrId, defaults to true
function hourglassOn(elemOrId, decendents) {
var elem=elemFromParam(elemOrId);
if (!elem) return;
if (typeof decendents==='undefined' || decendents===null) decendents=true;
if ($('style:contains("hourGlass")').length < 1) $('<style>').text('.hourGlass { cursor: wait !important; }').appendTo('head');
if ($('style:contains("hourGlassWithDecendents")').length < 1) $('<style>').text('.hourGlassWithDecendents, .hourGlassWithDecendents * { cursor: wait !important; }').appendTo('head');
elem.addClass(decendents ? 'hourGlassWithDecendents' : 'hourGlass');
}
// elemOrId - jquery element or element id, defaults to $('<body>')'
function hourglassOff(elemOrId) {
var elem=elemFromParam(elemOrId);
if (!elem) return;
elem.removeClass('hourGlass');
elem.removeClass('hourGlassWithDecendents');
}
function elemFromParam(elemOrId) {
var elem;
if (typeof elemOrId==='undefined' || elemOrId===null)
elem=$('body');
else if (typeof elemOrId === 'string' || elemOrId instanceof String)
elem=$('#'+elemOrId);
else
elem=$(elemOrId);
if (!elem || elem.length===0) {
console.log('elemFromParam no element !');
return null;
}
return elem;
}
With this you can do for example:
maskOn(); // transparent page mask
maskOn(null, {color:'gray', opacity:0.8}); // gray page mask with opacity
maskOff(); // remove page mask
maskOn(div); // transparent div mask
maskOn(divId, {color:'gray', hourglass:true}); // gray div mask with hourglass
maskOff(div); // remove div mask
see jsfiddle

function disableItems(divSelector){
var disableInputs = $(divSelector).find(":input").not("[disabled]");
disableInputs.attr("data-reenable", true);
disableInputs.attr("disabled", true);
}
function reEnableItems(divSelector){
var reenableInputs = $(divSelector).find("[data-reenable]");
reenableInputs.removeAttr("disabled");
reenableInputs.removeAttr("data-reenable");
}

Another way, in jQuery, would be to get the inner height, inner width and positioning of the containing DIV, and simply overlay another DIV, transparent, over the top the same size. This will work on all elements inside that container, instead of only the inputs.
Remember though, with JS disabled, you'll still be able to use the DIVs inputs/content. The same goes with the above answers too.

$("#yourdivid textarea, #yourdivid input, #yourdivid select").attr('disabled',true);

This css only/noscript solution adds an overlay above a fieldset (or a div or any other element), preventing interaction:
fieldset { position: relative; }
fieldset[disabled]::after { content: ''; display: inline-block; position: absolute; top: 0; left: 0; right: 0; bottom: 0; pointer-events: all; background: rgba(128,128,128,0.2); }
If you want an invisible i.e. transparent overlay, set the background to e.g. rgba(128,128,128,0), as it won't work without a background.
The above works for IE9+. The following much simpler css will work on IE11+
[disabled] { pointer-events: none; }
Chrome

If you are simply trying to stop people clicking and are not horrifically worried about security - I have found an absolute placed div with a z-index of 99999 sorts it fine. You can't click or access any of the content because the div is placed over it. Might be a bit simpler and is a CSS only solution until you need to remove it.

Its very easy to handle if you want to disable the pointer event
document.getElementById("appliedDatepicker").style.pointerEvents = "none";
or
if you want to enable,
document.getElementById("appliedDatepicker").style.pointerEvents = "auto";

EDIT:
Below I've used .on() method, instead use .bind() method
$(this).bind('click', false);
$(this).bind('contextmenu', false);
to remove your setting, you can use .unbind() method. Whereas the .off() method doesn't work as expected.
$(this).unbind('click', false);
$(this).unbind('contextmenu', false);
After researching hundreds of solutions! learning about pointer-events, below is what I did.
As #Kokodoko mentioned in his solution which is apt for all browsers except IE. pointer-events work in IE11 and not in the lower versions. I also noticed in IE11, pointer-events do not work on the child elements. And hence if we have something like below
<i class="car icon"></i><span>My Blog</span>
where span -is the child element, setting pointer-events: nonewont work
To overcome this problem I wrote a function which could act as pointer-events for IE and will work in the lower versions.
In JS File
DisablePointerEvents(".DisablePointerEvents");
function DisablePointerEvents(classId) {
$(classId).each(function () {
$(this).on('click', false );
$(this).on('contextmenu', false );
});
}
In CSS File
.DisablePointerEvents{
pointer-events: none;
opacity: 0.7;
cursor: default;
}
In HTML
<i class="car icon"></i><span>My Blog</span>
This faked the pointer-events scenario where pointer-events doesnt work and when the above condition of child elements occur.
JS Fiddle for the same
https://jsfiddle.net/rpxxrjxh/

the simpleset solution
look at my selector
$myForm.find('#fieldsetUserInfo input:disabled').prop("disabled", false);
the fieldsetUserInfo is div contains all inputs I want to disabled or Enable
hope this helps you

There are configurable javascript libraries that take in a html string or dom element and strip out undesired tags and attributes. These are known as html sanitizers. For example:
DOMPurify
Insane
sanitize-html
E.g. In DOMPurify
DOMPurify.sanitize('<div>abc<iframe//src=jAva&Tab;script:alert(3)>def</div>');
// becomes <div>abcdef</div>

Related

HTML Label doesn't trigger the respective input if the mouse gets moved while clicking in Firefox

In the following example, when you click on the label, the input changes state.
document.querySelector("label").addEventListener("click", function() {
console.log("clicked label");
});
label {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<input type="checkbox" id="1">
<label for="1">Label</label>
In Chrome, when you move the cursor between the mousedown and mouseup events the input still gets triggered, whereas in Firefox the checkbox doesn't change state.
Is there a way to fix this? (without using JavaScript event listeners)
Firefox version: 69.0.3 (64-bit)
Full set of actions when using chrome.
Press the button over the label
Move the cursor around (even outside the label) while still holding the button
Return the cursor back to the label
Release the button
Introduction
Although I specifically stated in the question that the answer shouldn't involve JavaScript, all the answers worked with JavaScript.
Since this seems to be a Firefox bug and most of the answers submitted at this point would require me to also alter the rest of my code, I decided to create a script that can be run once, will deal with all the labels regardless of when they are added to the dom and will have the least impact on my other scripts.
Solution - Example
var mutationConfiguration = {
attributes: true,
childList: true
};
if (document.readyState === "complete") onLoad();
else addEventListener("load", onLoad);
var managingDoms = [];
function onLoad() {
document.querySelectorAll("label[for]").forEach(manageLabel);
if (typeof MutationObserver === "function") {
var observer = new MutationObserver(function(list) {
list.forEach(function(item) {
({
"attributes": function() {
if (!(item.target instanceof HTMLLabelElement)) return;
if (item.attributeName === "for") manageLabel(item.target);
},
"childList": function() {
item.addedNodes.forEach(function(newNode) {
if (!(newNode instanceof HTMLLabelElement)) return;
if (newNode.hasAttribute("for")) manageLabel(newNode);
});
}
}[item.type])();
});
});
observer.observe(document.body, mutationConfiguration);
}
}
function manageLabel(label) {
if (managingDoms.includes(label)) return;
label.addEventListener("click", onLabelClick);
managingDoms.push(label);
}
function onLabelClick(event) {
if (event.defaultPrevented) return;
var id = this.getAttribute("for");
var target = document.getElementById(id);
if (target !== null) {
this.removeAttribute("for");
var self = this;
target.click();
target.focus();
setTimeout(function() {
self.setAttribute("for", id);
}, 0);
}
}
label {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
padding: 10px;
border: 1px solid black;
cursor: pointer;
}
<input type="checkbox" id="a">
<input type="text" id="b">
<label for="a">A</label>
<script>
setTimeout(function() {
var label = document.createElement("label");
label.setAttribute("for", "b");
label.textContent = "b";
document.body.appendChild(label);
}, 3E3);
</script>
Explanation
onLabelClick
The function onLabelClick needs to get called whenever a label gets clicked, it will check if the label has a corresponding input element. If it does, it will trigger it, remove the for attribute of the label so that the browsers don't have the bug won't re-trigger it and then use a setTimeout of 0ms to add the for attribute back once the event has bubbled up. This means event.preventDefault doesn't have to get called and thus no other actions/events will get cancelled. Also if I need to override this function I just have to add an event-listener that calls Event#preventDefault or removes the for attribute.
manageLabel
The function manageLabel accepts a label checks if it has already been added an event listener to avoid re-adding it, adds the listener if it hasn't already been added, and adds it to the list of labels have been managed.
onLoad
The function onLoad needs to get called when the page gets loaded so that the function manageLabel can be called for all the labels on the DOM at that moment. The function also uses a MutationObserver to catch any labels that get added, after the load has been fired (and the script has been run).
The code displayed above was optimized by Martin Barker.
I know you did not want JS Event listeners, but im thinking you mean to identify the movement this does not but is using mousedown instead of click (mousedown followed by mouseup).
While this is a known bug in Firefox you could get around it by using the mousedown event
I have had to change your id to be a valid one id's must start with a character
document.querySelector("label").addEventListener("mousedown", function(evt) {
console.log("clicked label");
// if you want to to check the checkbox when it happens,
let elmId = evt.target.getAttribute("for")
let oldState = document.querySelector("#"+elmId).checked;
setTimeout(() => {
if(oldState == document.querySelector("#"+elmId).checked){
document.querySelector("#"+elmId).checked = !oldState;
}
}, 150)
});
label {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
<input type="checkbox" id="valid_1">
<label for="valid_1">Label</label>
No. This looks like a firefox bug and not an issue with your code. I don't believe there is a css workaround for this behavior.
You may be able to report it to Mozilla and get the issue fixed, but I wouldn't rely on that. https://bugzilla.mozilla.org/home
For a potential workaround I would suggested triggering the event on mouseup instead.
Without javascript, when you click the label that has its "for" value the same as an inputs "id" value then the input gets clicked, but this is not consistent amongst browsers.
If a browser does follow the above, then your javascript click event will cancel out the effect, which ends up doing nothing.
A solution
To have consistency amongst browsers you could adopt a different strategy:
Onload dynamically change all the attribute 'for' for 'data-for', so it nulls the original browser affect. Then you can apply your click event to each label.
var replaceLabelFor = function () {
var $labels = document.querySelectorAll('label');
var arrLabels = Array.prototype.slice.call($labels);
arrLabels.forEach(function (item) {
var att = document.createAttribute('data-for');
att.value = String(this.for);
item.setAttributeNode(att);
item.removeAttribute('for')
});
}
var applyMyLabelClick() {
document.querySelector("label").addEventListener("click", function() {
console.log("clicked label");
});
}
// x-browser handle onload
document.attachEvent("onreadystatechange", function(){
if(document.readyState === "complete"){
document.detachEvent("onreadystatechange", arguments.callee);
replaceLabelFor();
applyMyLabelClick();
}
});
Attaching the event to the document and targeting the element you require in there ought to sort this issue.
​ $(document).on('click', '.item', function(event) {});
From reading on this topic in the past, it’s down to Firefox understanding your action as an attempt to drag the element however, since user select is none, it just prevents the default behaviour.
This is based on fairly limited knowledge but it seems to be a known bug/quirk and there is a few articles floating around supporting this.

JavaScript/jQuery code optimization

I'm learning JavaScript and jQuery and currently I'm dealing with following code:
$("#hrefBlur0").hover(function() {
$("#imgBlur0").toggleClass("blur frame");
});
$("#hrefBlur1").hover(function() {
$("#imgBlur1").toggleClass("blur frame");
});
$("#hrefBlur2").hover(function() {
$("#imgBlur2").toggleClass("blur frame");
});
$("#hrefBlur3").hover(function() {
$("#imgBlur3").toggleClass("blur frame");
});
$("#hrefBlur4").hover(function() {
$("#imgBlur4").toggleClass("blur frame");
});
$("#hrefBlur5").hover(function() {
$("#imgBlur5").toggleClass("blur frame");
});
$("#hrefBlur6").hover(function() {
$("#imgBlur6").toggleClass("blur frame");
});
$("#hrefBlur7").hover(function() {
$("#imgBlur7").toggleClass("blur frame");
});
The code is supposed to remove blur effect from an image while I hoover a cursor on a href link on the website. I'm wondering if I can do it faster, with fewer lines of code.
I tried:
for (var i = 0; i < 8; i++) {
$("#hrefBlur" + i).hover(function() {
$("#imgBlur" + i).toggleClass("blur frame");
});
}
But that code doesn't work.
Here's the JS fiddle: link
You can set a class to the elements and select that class, for example let's say you want to use "blurMeContainer" for the container, you can do something like this:
$(".blurMeContainer").hover(function(el){
$(this).find("img").toggleClass("blur frame");
});
The trick is that you must be aware that jQuery applies the events to the element, so inside the events function, the "this" accessor is the element involved in the event, than you can use the $ function in the selector in order to have his corrispective jQuery element, and then you can use "find" method to find any img tag inside the jQuery element. Obviously this could work only if you have a single image in the container, if you need to identify only one image in a set of images inside a single container, assign a class to that image (IE: "blurMe") and change the code in this way:
$(".blurMeContainer").hover(function(el){
$(this).find(".blurMe").toggleClass("blur frame");
});
Use attributeStartsWith selector , that Selects elements that have the specified attribute with a value beginning exactly with a given string:
$('a[id^="hrefBlur"]').hover(function() {
$(this).find('img').toggleClass("blur frame");
});
Here's working fiddle
Although doing what your after can be done with JQuery. I personally think it's the wrong tool for the Job.
CSS, will do all this for you, in a much simpler way. No Javascript needed. With the added benefit of the browser optimisations.
.blurme {
filter: blur(3px);
cursor: pointer;
transition: color 2s, filter 1s;
}
.blurme:hover {
filter: none;
color: red;
font-weight: bold;
}
<span class="blurme">One</span>
<span class="blurme">Two</span>
<span class="blurme">Three</span>
<span class="blurme">Four</span>
<span class="blurme">Five</span>
<span class="blurme">Six</span>
<br>
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">
<img class="blurme" src="http://placekitten.com.s3.amazonaws.com/homepage-samples/96/139.jpg">

How do I change an attribute or class using only Javascript?

I would like to change the styling attribute values of all elements that have the class "post-feature" and contain an attribute value of "http"
So the div element will look like the following:
<div class="post-feature" style="backgroundimage:url(http://local.test.com/test_image.jpg);">
So far the http check works. But I am not able to set the attribute value.
I have the following code
var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");
if (features.includes("http")) {
features.setAttribute("background-color", "orange");
} else {
alert('no change');
}
You can use querySelectorAll('.post-feature[style*="http"]') to find those elements.
Then simply iterate through them and i.e. set their background color with
element.style.backgroundColor = 'orange';
Now, if you want to make sure you only target elements having a background-image and http, you can use this selector:
querySelectorAll('.post-feature[style*="http"][style*="background-image"]')
Also, by adding an i (or I) just before the end bracket [style*="http"i], the value will be compared case-insensitively.
window.addEventListener('load', function() {
var elements = document.querySelectorAll('.post-feature[style*="http"]');
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = 'orange'; /* add propert value */
/* replace class
elements[i].className = 'myClass';
*/
/* add a class
elements[i].classList.add('myClass');
*/
}
/* temp log */
console.log('Found ', elements.length,' element(s)');
})
div {
height: 40px;
background-color: gray;
}
div + div {
margin-top: 10px;
}
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"></div>
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"></div>
Updated
To only change styling, like colors etc., you don't even need a script, you can use CSS alone
div {
height: 40px;
background-color: gray;
}
div + div {
margin-top: 10px;
}
/* for elements that contain "http" and "background-image" */
.post-feature[style*="http"i][style*="background-image"i] {
background-color: orange;
}
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"></div>
<div class="post-feature" style="background-image:url(HTTP://local.test.com/test_image.jpg);"></div>
<div class="post-feature"></div>
As a note, and as discussed in a few comments, if to make sure it is the background-image property that also contain the http in its url(), you can adjust the selector to this, which as well can be used without any script, as a CSS rule
.post-feature[style*="background-image:url(http"i] {
background-color: orange;
}
The above selector can of course also be used in the first sample, like this
querySelectorAll('.post-feature[style*="background-image:url(http"i]')
First, you can use querySelctorAll() with a CSS query that selects the elements with the class you desire and, in most cases, you should use this instead of getElementsByClassName() as that returns a "live node list" that causes the DOM to be re-scanned every time you access it.
Next, setAttribute() is for setting HTML element attributes. You are asking to change the value of a CSS property. While that could be accomplished with setAttribute('style', value), it is very "old-school" and not the best approach, nor is getAttribute('style') the best way to read a CSS property value (it won't work if the CSS was set from a style sheet).
Also, your code is trying to access: backgroundimage, but the property is accessed as background-image when working in CSS and backgroundImage when accessing it via JavaScript.
To access the inline styles applied to an HTML element, just access the style property of that element, followed by the name of the CSS property you are interested in. For example:
var bColor = element.style.backgroundColor;
If the style has been applied to the element from an internal style sheet or an external style sheet, the above approach won't work for you and you'll need to get it another way, via window.getComputedStyle():
var bColor = window.getComputedStyle(element, null).backgroundColor;
But, note that getComputedStyle() doesn't always return the same value that you set - - it's the value after the browser has computed all factors. In this case, even paths that you wrote as relative references (without the "http") will be returned as absolute paths (with the http).
So, here is a modern approach that correctly checks only the background-image CSS property for the presence of http.
NOTE: This solution tests for http specifically in the background-image property. Unlike most of the other answers given, this code will correctly ignore http in other CSS properties besides background-image. Examine the CSS of the last div to see this in action.
// querySelectorAll() is more efficient than getElementsByClassName()
var features = document.querySelectorAll(".post-feature");
// Loop over the list
for(var i = 0; i < features.length; i++){
// Get access to the background-image property (called backgroundImage from JavaScript) value,
// convert that value to lower case and check to see if "http" is in that value
if(features[i].style.backgroundImage.toLowerCase().indexOf("http") > -1){
// Set the CSS background-color property (called "backgroundColor" in JavaScript) to orange:
features[i].style.backgroundColor = "orange";
// Just for testing:
features[i].textContent = features[i].style.backgroundImage;
} else {
alert("No change");
}
}
.post-feature { width:100%; height:50px; border:1px solid black; background-color:gray; color:yellow; }
<!-- The correct CSS property is "background-image", not "backgroundimage" -->
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature" style="background-image:url(test_image.jpg);"></div>
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);"></div>
<div class="post-feature"
style="border-image: url('http:///images/border.png') 30 30 repeat;background-image:url(test_image.jpg);">I have "http" in one of my CSS properties, but not "background-image", so I shouldn't be orange.</div>
i think some wrong in your code, try this code
element.setAttribute("style", "background-color: orange;"); // bad
or
element.style.backgroundColor = "orange"; // good
Use element.style.backgroundColor and indexOf
var features = document.getElementsByClassName(".post-feature")[0].getAttribute("style");
if (features.indexOf("http") > -1) {
features.style.backgroundColor = "orange";
} else {
alert('no change');
}
check this fiddle
https://jsfiddle.net/vywk72j8/2/
<div class="post-feature" style="background-image:url(http://local.test.com/test_image.jpg);">
tt</div>
var feature = document.getElementsByClassName("post-feature")[0];
if (feature.style.backgroundImage.indexOf("http") !== -1) {
feature.style.backgroundColor = "orange";
} else {
alert('no change');
}
In your code, you are fetching the attribute value in features
var features = document.getElementsByClassName(".post-feature")
[0].getAttribute("style");
Here features is a string containing attribute value, not an element so you cannot use it to set value.

Dynamically changing cursor/setting cur files

How can I dynamically change the style of cursors on my div using JS or CSS?
Because I have multiple situations...
I've tried the code below:
div.addEventListener("mouseover", function(evt) {
if (tool == "BC"){
div.style.cursor = "url(/icons/bc.cur)";
}
if (tool == "pan"){
div.style.cursor = "url(/icons/pan.cur)";
}
}
Assuming you're using conditional comments as in html5 boilerplate you could define this style (note the different syntax for newer browser — see MDN docs for further information):
div.bc { cursor : url(/icons/bc.cur), auto; }
div.pan { cursor : url(/icons/pan.cur), auto; }
/* style for IE<9 */
.lt-ie9 div.bc { cursor : url(/icons/bc.cur); }
.lt-ie9 div.pan { cursor : url(/icons/pan.cur); }
and, assuming for simplicity that your div hasn't any class applied, just change your js code like so:
div.addEventListener("mouseover", function(evt) {
this.className = tool.toLowerCase();
}
This approach will ensure good scalability, since in case you have another cursor to list, the javascript doesn't need to be modified further, just add a new couple of css rules. Furthermore you will totally keep off css from javascript, thus your javascript has a better mantainability.

How do I check if an element is hidden in jQuery?

How do I toggle the visibility of an element using .hide(), .show(), or .toggle()?
How do I test if an element is visible or hidden?
Since the question refers to a single element, this code might be more suitable:
// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");
// The same works with hidden
$(element).is(":hidden");
It is the same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ.
We use jQuery's is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false.
You can use the hidden selector:
// Matches all elements that are hidden
$('element:hidden')
And the visible selector:
// Matches all elements that are visible
$('element:visible')
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
// 'element' is hidden
}
The above method does not consider the visibility of the parent. To consider the parent as well, you should use .is(":hidden") or .is(":visible").
For example,
<div id="div1" style="display:none">
<div id="div2" style="display:block">Div2</div>
</div>
The above method will consider div2 visible while :visible not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions :visible will not work.
None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden?". Neither :visible nor :hidden will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):
$(".item").each(function() {
if ($(this).css("visibility") == "hidden") {
// handle non visible state
} else {
// handle visible state
}
});
From How do I determine the state of a toggled element?
You can determine whether an element is collapsed or not by using the :visible and :hidden selectors.
var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');
If you're simply acting on an element based on its visibility, you can just include :visible or :hidden in the selector expression. For example:
$('#myDiv:visible').animate({left: '+=200px'}, 'slow');
Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.
So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible") or filter(":hidden") followed by chaining it with the action you want to take.
So instead of an if statement, like this:
if ($('#btnUpdate').is(":visible"))
{
$('#btnUpdate').animate({ width: "toggle" }); // Hide button
}
Or more efficient, but even uglier:
var button = $('#btnUpdate');
if (button.is(":visible"))
{
button.animate({ width: "toggle" }); // Hide button
}
You can do it all in one line:
$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
The :visible selector according to the jQuery documentation:
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.
This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none), ignoring the parents visibility, you will find that doing .css("display") == 'none' is not only faster, but will also return the visibility check correctly.
If you want to check visibility instead of display, you should use: .css("visibility") == "hidden".
Also take into consideration the additional jQuery notes:
Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").
Also, if you are concerned about performance, you should check Now you see me… show/hide performance (2010-05-04). And use other methods to show and hide elements.
How element visibility and jQuery works;
An element could be hidden with display:none, visibility:hidden or opacity:0. The difference between those methods:
display:none hides the element, and it does not take up any space;
visibility:hidden hides the element, but it still takes up space in the layout;
opacity:0 hides the element as "visibility:hidden", and it still takes up space in the layout; the only difference is that opacity lets one to make an element partly transparent;
if ($('.target').is(':hidden')) {
$('.target').show();
} else {
$('.target').hide();
}
if ($('.target').is(':visible')) {
$('.target').hide();
} else {
$('.target').show();
}
if ($('.target-visibility').css('visibility') == 'hidden') {
$('.target-visibility').css({
visibility: "visible",
display: ""
});
} else {
$('.target-visibility').css({
visibility: "hidden",
display: ""
});
}
if ($('.target-visibility').css('opacity') == "0") {
$('.target-visibility').css({
opacity: "1",
display: ""
});
} else {
$('.target-visibility').css({
opacity: "0",
display: ""
});
}
Useful jQuery toggle methods:
$('.click').click(function() {
$('.target').toggle();
});
$('.click').click(function() {
$('.target').slideToggle();
});
$('.click').click(function() {
$('.target').fadeToggle();
});
This works for me, and I am using show() and hide() to make my div hidden/visible:
if( $(this).css('display') == 'none' ){
/* your code goes here */
} else {
/* alternate logic */
}
You can also do this using plain JavaScript:
function isRendered(domObj) {
if ((domObj.nodeType != 1) || (domObj == document.body)) {
return true;
}
if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
return isRendered(domObj.parentNode);
} else if (window.getComputedStyle) {
var cs = document.defaultView.getComputedStyle(domObj, null);
if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
return isRendered(domObj.parentNode);
}
}
return false;
}
Notes:
Works everywhere
Works for nested elements
Works for CSS and inline styles
Doesn't require a framework
I would use CSS class .hide { display: none!important; }.
For hiding/showing, I call .addClass("hide")/.removeClass("hide"). For checking visibility, I use .hasClass("hide").
It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle() or .animate() methods.
Demo Link
$('#clickme').click(function() {
$('#book').toggle('slow', function() {
// Animation complete.
alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
Click here
</div>
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>
Source (from my blog):
Blogger Plug n Play - jQuery Tools and Widgets: How to See if Element is hidden or Visible Using jQuery
ebdiv should be set to style="display:none;". It works for both show and hide:
$(document).ready(function(){
$("#eb").click(function(){
$("#ebdiv").toggle();
});
});
One can simply use the hidden or visible attribute, like:
$('element:hidden')
$('element:visible')
Or you can simplify the same with is as follows.
$(element).is(":visible")
Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length).
When testing an element against :hidden selector in jQuery it should be considered that an absolute positioned element may be recognized as hidden although their child elements are visible.
This seems somewhat counter-intuitive in the first place – though having a closer look at the jQuery documentation gives the relevant information:
Elements can be considered hidden for several reasons: [...] Their width and height are explicitly set to 0. [...]
So this actually makes sense in regards to the box-model and the computed style for the element. Even if width and height are not set explicitly to 0 they may be set implicitly.
Have a look at the following example:
console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
position: absolute;
left: 10px;
top: 10px;
background: #ff0000;
}
.bar {
position: absolute;
left: 10px;
top: 10px;
width: 20px;
height: 20px;
background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar"></div>
</div>
Update for jQuery 3.x:
With jQuery 3 the described behavior will change! Elements will be considered visible if they have any layout boxes, including those of zero width and/or height.
JSFiddle with jQuery 3.0.0-alpha1:
http://jsfiddle.net/pM2q3/7/
The same JavaScript code will then have this output:
console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false
expect($("#message_div").css("display")).toBe("none");
$(document).ready(function() {
if ($("#checkme:hidden").length) {
console.log('Hidden');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
<span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
<br>Product: Salmon Atlantic
<br>Specie: Salmo salar
<br>Form: Steaks
</div>
To check if it is not visible I use !:
if ( !$('#book').is(':visible')) {
alert('#book is not visible')
}
Or the following is also the sam, saving the jQuery selector in a variable to have better performance when you need it multiple times:
var $book = $('#book')
if(!$book.is(':visible')) {
alert('#book is not visible')
}
Use class toggling, not style editing . . .
Using classes designated for "hiding" elements is easy and also one of the most efficient methods. Toggling a class 'hidden' with a Display style of 'none' will perform faster than editing that style directly. I explained some of this pretty thoroughly in Stack Overflow question Turning two elements visible/hidden in the same div.
JavaScript Best Practices and Optimization
Here is a truly enlightening video of a Google Tech Talk by Google front-end engineer Nicholas Zakas:
Speed Up Your Javascript (YouTube)
After all, none of examples suits me, so I wrote my own.
Tests (no support of Internet Explorer filter:alpha):
a) Check if the document is not hidden
b) Check if an element has zero width / height / opacity or display:none / visibility:hidden in inline styles
c) Check if the center (also because it is faster than testing every pixel / corner) of element is not hidden by other element (and all ancestors, example: overflow:hidden / scroll / one element over another) or screen edges
d) Check if an element has zero width / height / opacity or display:none / visibility:hidden in computed styles (among all ancestors)
Tested on
Android 4.4 (Native browser/Chrome/Firefox), Firefox (Windows/Mac), Chrome (Windows/Mac), Opera (Windows Presto/Mac WebKit), Internet Explorer (Internet Explorer 5-11 document modes + Internet Explorer 8 on a virtual machine), and Safari (Windows/Mac/iOS).
var is_visible = (function () {
var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,
y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,
relative = !!((!x && !y) || !document.elementFromPoint(x, y));
function inside(child, parent) {
while(child){
if (child === parent) return true;
child = child.parentNode;
}
return false;
};
return function (elem) {
if (
document.hidden ||
elem.offsetWidth==0 ||
elem.offsetHeight==0 ||
elem.style.visibility=='hidden' ||
elem.style.display=='none' ||
elem.style.opacity===0
) return false;
var rect = elem.getBoundingClientRect();
if (relative) {
if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;
} else if (
!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||
(
rect.top + elem.offsetHeight/2 < 0 ||
rect.left + elem.offsetWidth/2 < 0 ||
rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||
rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)
)
) return false;
if (window.getComputedStyle || elem.currentStyle) {
var el = elem,
comp = null;
while (el) {
if (el === document) {break;} else if(!el.parentNode) return false;
comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;
el = el.parentNode;
}
}
return true;
}
})();
How to use:
is_visible(elem) // boolean
Example of using the visible check for adblocker is activated:
$(document).ready(function(){
if(!$("#ablockercheck").is(":visible"))
$("#ablockermsg").text("Please disable adblocker.").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>
"ablockercheck" is a ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.
$(document).ready(function() {
var visible = $('#tElement').is(':visible');
if(visible) {
alert("visible");
// Code
}
else
{
alert("hidden");
}
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<input type="text" id="tElement" style="display:block;">Firstname</input>
You need to check both... Display as well as visibility:
if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
// The element is not visible
} else {
// The element is visible
}
If we check for $(this).is(":visible"), jQuery checks for both the things automatically.
Simply check visibility by checking for a boolean value, like:
if (this.hidden === false) {
// Your code
}
I used this code for each function. Otherwise you can use is(':visible') for checking the visibility of an element.
Because Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout (as described for jQuery :visible Selector) - we can check if element is really visible in this way:
function isElementReallyHidden (el) {
return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}
var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
if (isElementReallyHidden(this)) {
booElementReallyShowed = false;
}
});
But what if the element's CSS is like the following?
.element{
position: absolute;left:-9999;
}
So this answer to Stack Overflow question How to check if an element is off-screen should also be considered.
A function can be created in order to check for visibility/display attributes in order to gauge whether the element is shown in the UI or not.
function checkUIElementVisible(element) {
return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}
Working Fiddle
Also here's a ternary conditional expression to check the state of the element and then to toggle it:
$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });
if($('#postcode_div').is(':visible')) {
if($('#postcode_text').val()=='') {
$('#spanPost').text('\u00a0');
} else {
$('#spanPost').text($('#postcode_text').val());
}

Categories