Related
my demo jsfiddle
What I want is a reverse transition when I click the < li > again, but the commentted code didn`t work,and the code below works fine
let dbclickre = true;
function flipped() {
if (dbclickre) {
document.querySelector(".linkrec").setAttribute("Id", "flipped");
} else {
document.querySelector(".linkrec").removeAttribute("Id", "flipped")
}
dbclickre = !dbclickre;
}
below is the commentted code (I think when i firstly click the last < li > ,js will excute the if statement(and indeed it works fine),but when i click again , the else statement didn't excude(but i have set #flipped .reverse {background: whitesmoke} ) . why this happening???)
// const dbclickre = document.querySelector(".reverse");
// function flipped() {
// if (dbclickre.style.backgroundColor = 'white') {
// document.querySelector(".linkrec").setAttribute("Id", "flipped");
// } else {
// document.querySelector(".linkrec").removeAttribute("Id", "flipped")
// }
// }
Instead of relying on background color for checking the state of flip, you could check for existence of Id attribute. Here the the changed code:
const dbclickre = document.querySelector(".reverse");
function flipped() {
if ( document.querySelector(".linkrec").getAttribute("Id") == undefined ) {
document.querySelector(".linkrec").setAttribute("Id", "flipped");
} else {
document.querySelector(".linkrec").removeAttribute("Id", "flipped")
}
}
Edit:
Why element.style would not work?
From MDN Web Docs:
The style property is used to get as well as set the inline style of an element.
Hence, the style property would not work with embedded or external CSS.
Also, it may not be a good idea to use hard-coded colors as the condition, because changing colors in the respective CSS classes would completely break the functionality.
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.
How can JavaScript change CSS :hover properties?
For example:
HTML
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
CSS
table td:hover {
background:#ff0000;
}
How can the td :hover properties be modified to, say, background:#00ff00, with JavaScript? I know I could access the style background property using JavaScript with:
document.getElementsByTagName("td").style.background="#00ff00";
But I don't know of a .style JavaScript equivalent for :hover.
Pseudo classes like :hover never refer to an element, but to any element that satisfies the conditions of the stylesheet rule. You need to edit the stylesheet rule, append a new rule, or add a new stylesheet that includes the new :hover rule.
var css = 'table td:hover{ background-color: #00ff00 }';
var style = document.createElement('style');
if (style.styleSheet) {
style.styleSheet.cssText = css;
} else {
style.appendChild(document.createTextNode(css));
}
document.getElementsByTagName('head')[0].appendChild(style);
You can't change or alter the actual :hover selector through Javascript. You can, however, use mouseenter to change the style, and revert back on mouseleave (thanks, #Bryan).
Pretty old question so I figured I'll add a more modern answer. Now that CSS variables are widely supported they can be used to achieve this without the need for JS events or !important.
Taking the OP's example:
<table>
<tr>
<td>Hover 1</td>
<td>Hover 2</td>
</tr>
</table>
We can now do this in the CSS:
table td:hover {
// fallback in case we need to support older/non-supported browsers (IE, Opera mini)
background: #ff0000;
background: var(--td-background-color);
}
And add the hover state using javascript like so:
const tds = document.querySelectorAll('td');
tds.forEach((td) => {
td.style.setProperty('--td-background-color', '#00ff00');
});
Here's a working example https://codepen.io/ybentz/pen/RwPoeqb
What you can do is change the class of your object and define two classes with different hover properties. For example:
.stategood_enabled:hover { background-color:green}
.stategood_enabled { background-color:black}
.stategood_disabled:hover { background-color:red}
.stategood_disabled { background-color:black}
And this I found on:
Change an element's class with JavaScript
function changeClass(object,oldClass,newClass)
{
// remove:
//object.className = object.className.replace( /(?:^|\s)oldClass(?!\S)/g , '' );
// replace:
var regExp = new RegExp('(?:^|\\s)' + oldClass + '(?!\\S)', 'g');
object.className = object.className.replace( regExp , newClass );
// add
//object.className += " "+newClass;
}
changeClass(myInput.submit,"stategood_disabled"," stategood_enabled");
Sorry to find this page 7 years too late, but here is a much simpler way to solve this problem (changing hover styles arbitrarily):
HTML:
<button id=Button>Button Title</button>
CSS:
.HoverClass1:hover {color: blue !important; background-color: green !important;}
.HoverClass2:hover {color: red !important; background-color: yellow !important;}
JavaScript:
var Button=document.getElementById('Button');
/* Clear all previous hover classes */
Button.classList.remove('HoverClass1','HoverClass2');
/* Set the desired hover class */
Button.classList.add('HoverClass1');
If it fits your purpose you can add the hover functionality without using css and using the onmouseover event in javascript
Here is a code snippet
<div id="mydiv">foo</div>
<script>
document.getElementById("mydiv").onmouseover = function()
{
this.style.backgroundColor = "blue";
}
</script>
You can use mouse events to control like hover.
For example, the following code is making visible when you hover that element.
var foo = document.getElementById("foo");
foo.addEventListener('mouseover',function(){
foo.style.display="block";
})
foo.addEventListener('mouseleave',function(){
foo.style.display="none";
})
I'd recommend to replace all :hover properties to :active when you detect that device supports touch. Just call this function when you do so as touch()
function touch() {
if ('ontouchstart' in document.documentElement) {
for (var sheetI = document.styleSheets.length - 1; sheetI >= 0; sheetI--) {
var sheet = document.styleSheets[sheetI];
if (sheet.cssRules) {
for (var ruleI = sheet.cssRules.length - 1; ruleI >= 0; ruleI--) {
var rule = sheet.cssRules[ruleI];
if (rule.selectorText) {
rule.selectorText = rule.selectorText.replace(':hover', ':active');
}
}
}
}
}
}
This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:
$(".hoverCell").bind('mouseover', function() {
var old_color = $(this).css("background-color");
$(this)[0].style.backgroundColor = '#ffff00';
$(".hoverCell").bind('mouseout', function () {
$(this)[0].style.backgroundColor = old_color;
});
});
This requires setting the Class for each of the cells you want to highlight to "hoverCell".
I had this need once and created a small library for, which maintains the CSS documents
https://github.com/terotests/css
With that you can state
css().bind("TD:hover", {
"background" : "00ff00"
});
It uses the techniques mentioned above and also tries to take care of the cross-browser issues. If there for some reason exists an old browser like IE9 it will limit the number of STYLE tags, because the older IE browser had this strange limit for number of STYLE tags available on the page.
Also, it limits the traffic to the tags by updating tags only periodically. There is also a limited support for creating animation classes.
Declare a global var:
var td
Then select your guiena pig <td> getting it by its id, if you want to change all of them then
window.onload = function () {
td = document.getElementsByTagName("td");
}
Make a function to be triggered and a loop to change all of your desired td's
function trigger() {
for(var x = 0; x < td.length; x++) {
td[x].className = "yournewclass";
}
}
Go to your CSS Sheet:
.yournewclass:hover { background-color: #00ff00; }
And that is it, with this you are able to to make all your <td> tags get a background-color: #00ff00; when hovered by changing its css propriety directly (switching between css classes).
For myself, I found the following option: from https://stackoverflow.com/a/70557483/18862444
const el = document.getElementById('elementId');
el.style.setProperty('--focusHeight', newFocusHeight);
el.style.setProperty('--focusWidth', newFocusWidth);
.my-class {
--focusHeight: 32px;
--focusWidth: 256px;
}
.my-class:focus {
height: var(--focusHeight);
width: var(--focusWidth);
}
You can make a CSS variable, and then change it in JS.
:root {
--variableName: (variableValue);
}
to change it in JS, I made these handy little functions:
var cssVarGet = function(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name);
};
and
var cssVarSet = function(name, val) {
document.documentElement.style.setProperty(name, val);
};
You can make as many CSS variables as you want, and I haven't found any bugs in the functions;
After that, all you have to do is embed it in your CSS:
table td:hover {
background: var(--variableName);
}
And then bam, a solution that just requires some CSS and 2 JS functions!
Had some same problems, used addEventListener for events "mousenter", "mouseleave":
let DOMelement = document.querySelector('CSS selector for your HTML element');
// if you want to change e.g color:
let origColorStyle = DOMelement.style.color;
DOMelement.addEventListener("mouseenter", (event) => { event.target.style.color = "red" });
DOMelement.addEventListener("mouseleave", (event) => { event.target.style.color = origColorStyle })
Or something else for style when cursor is above the DOMelement.
DOMElement can be chosen by various ways.
I was researching about hover, to be able to implement them in the button label and make the hover effect
<button type="submit"
style=" background-color:cornflowerblue; padding:7px; border-radius:6px"
onmouseover="this.style.cssText ='background-color:#a8ff78; padding:7px; border-radius:6px;'"
onmouseout="this.style.cssText='background-color:cornflowerblue; padding:7px; border-radius:6px'"
#click="form1()">
Login
</button>
You can create a class in css
.hover:hover {
background: #ff0000;
}
and then add it dynamically
const columns = document.querySelectorAll('table td');
for (let i = 0; i < columns.length; i++) {
columns[i].classList.add('hover');
}
But your css and js files should be connected in index.html
const tds = document.querySelectorAll('td');
tds.forEach((td,index) => {
td.addEventListener("mouseover", ()=>hover(index))
td.addEventListener("mouseout", ()=>normal(index))
});
function hover(index){
tds[index].style.background="red";
}
function normal(index){
tds[index].style.background="yellow";
}
Try this code it will work fine .
If you use lightweight html ux lang, check here an example, write:
div root
.onmouseover = ev => {root.style.backgroundColor='red'}
.onmouseleave = ev => {root.style.backgroundColor='initial'}
The code above performes the css :hover metatag.
Figured out how to change the class of a div/link/whatever onclick with JS. Here's a quick demo: http://nerdi.net/classchangetest.html
Now what I'm trying to figure out is how I can revert the previously clicked link to it's old class (or "deactivate") when clicking a new link.
Any ideas? Thanks!
function changeCssClass(navlink)
{
var links=document.getElementsByTagName('a');
for(var i=0, n=links.length; i<n; i++)
{
links[i].className='redText';
}
document.getElementById(navlink).className = 'blueText';
}
With this code all links will be red and lust clicked will be blue.
I hope it will be helpfull.
function changeCssClass(ele, add_class) {
// if add_class is not passed, revert
// to old className (if present)
if (typeof add_class == 'undefined') {
ele.className = typeof ele._prevClassName != 'undefined' ? ele._prevClassName : '';
} else {
ele._prevClassName = ele.className || '';
ele.className = add_class;
}
}
Try it here: http://jsfiddle.net/Zn7BL/
Use it:
// add "withClass"
changeCssClass(document.getElementById('test'), 'withClass');
// revert to original
changeCssClass(document.getElementById('test'));
It is a much better to post your code here, it makes it easier for those reading the question and for others searching later. Linked examples are unreliable and likely won't persist for long.
Copying from the link (and formatting for posting):
<style type="text/css">
.redText, .blueText { font-family: Arial; }
.redText { color : red; }
.blueText { color : blue; }
</style>
<script language="javascript" type="text/javascript">
The language attribute has been deprecated for a very long time, it should not be used. The type attribute is required, so keep that.
function changeCssClass(navlink)
The HTML class attribute is not sepecifically for CSS, it is used to group elements. A better name might be changeClassName.
{
if(document.getElementById(navlink).className=='redText')
{
document.getElementById(navlink).className = 'blueText';
}
else
{
document.getElementById(navlink).className = 'redText';
}
}
</script>
Link 1<br><br>
When called, the function associated with an inline listener will have its this keyword set to the element, so you can call the function as:
<a ... onclick="changeCssClass(this);" ...>
Then you don't have to pass the ID and you don't need getElementById in the function.
You might consider a function that "toggles" the class: adding it if it's not present, or removed if it is. You'll need to write some small functions like hasClass, addClass and removeClass, then your listener can be:
function toggleClass(el, className) {
if (hasClass(el, className) {
removeClass(el, className);
} else {
addClass(el, className);
}
}
Then give your links a default style using a style rule (i.e. apply the redText style to all links), then just add and remove the blueText class.
You might also consider putting a single function on a parent of the links to handle clicks from A elements — i.e. event delegation.
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	script:alert(3)>def</div>');
// becomes <div>abcdef</div>