Changing a Switchery checkbox state from code - javascript
How do I programatically change a jQuery Switchery checkbox state from checked to unchecked (and vice versa)?
I tried using global_switch_sound.prop('checked', true) on the checkbox element but it doesn't work.
HTML:
<input id="sound-active-input" type="checkbox" />
JavaScript:
global_switch_sound = new Switchery(document.querySelector('#sound-active-input'));
Try this:
$('.switchery').click();
It should trigger a click and switch.
OR this:
$('.switchery').trigger('click');
If anyone is like me and wanted a solution that goes beyond ".click()"ing the DOM. The following function takes the Switchery object and a boolean to indicate whether the switch should be checked or unchecked(true/ false respectively):
function setSwitchery(switchElement, checkedBool) {
if((checkedBool && !switchElement.isChecked()) || (!checkedBool && switchElement.isChecked())) {
switchElement.setPosition(true);
switchElement.handleOnchange(true);
}
}
Example usage:
var mySwitch = new Switchery($('#mySwitchCheck')[0], {
size:"small",
color: '#0D74E9'
});
//Checks the switch
setSwitchery(mySwitch, true);
//Unchecks the switch
setSwitchery(mySwitch, false);
Hope this helps someone else
Try this:
function changeSwitchery(element, checked) {
if ( ( element.is(':checked') && checked == false ) || ( !element.is(':checked') && checked == true ) ) {
element.parent().find('.switchery').trigger('click');
}
}
Example usage:
var element = $('#sound-active-input');
changeSwitchery(element, false);
First you have to store all the switches in an array during initialization
var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
switchery[html.getAttribute('id')] = new Switchery(html);
});
and create a local function to toggle switch like this
toggleSwitchery(id)
{
var s = switchery[id];
s.setPosition(true);
s.handleOnchange(true);
}
this worked for me.
In case you face any UI issue i.e. switch moves some extra pixels then open switchery.js and replace jack.offsetWidth by 30 in Switchery.prototype.setPosition function
You can simplify this:
// Uncheck: first set checked property to 'true', then uncheck to force UI update
$(".switchery").prop('checked', false).trigger("click");
// Check
$(".switchery").prop('checked', true).trigger("click");
function toggleSwitch(switch_elem, on) {
if (on){ // turn it on
if ($(switch_elem)[0].checked){ // it already is so do
// nothing
}else{
$(switch_elem).trigger('click').attr("checked", "checked"); // it was off, turn it on
}
}else{ // turn it off
if ($(switch_elem)[0].checked){ // it's already on so
$(switch_elem).trigger('click').removeAttr("checked"); // turn it off
}else{ // otherwise
// nothing, already off
}
}
}
call by using
toggleSwitch("#switch_element", true);
toggleSwitch("#switch_element", false);
Needs error checking and stuff but works well, requires jQuery and tested on Switchery 0.8.1 which came packaged with a prebuilt theme I've been using (Altair Admin)
Simple set like this with your checkbox id,
$('#sound-active-input').prop('checked', true);
DEMO http://jsfiddle.net/yeyene/VHZY8/2/
When you need to check/uncheck all switchery checkboxes the solution with JQuery is:
$( '.js-switches' ).each( function() {
// for checking
if ( !this.checked ) $( this ).trigger( 'click' );
// for unchecking
if ( this.checked ) $( this ).trigger( 'click' );
} );
hope it helps.
try this:
function changeSwitch(switch_id,active) {
var check = document.querySelector(switch_id);
//console.log("check",switch_id,check.checked,"to",active);
if ( !check.checked && active ){
var c = $(check).next('span').attr("class").replace("switchery ","");
var l = {"switchery-large":"26px","switchery-small":"13px","switchery-default":"20px"};
$(check).prop("checked",true).next('span').attr("style","box-shadow: rgb(38, 185, 154) 0px 0px 0px 16px inset; border-color: rgb(38, 185, 154); background-color: rgb(38, 185, 154); transition: border 0.4s, box-shadow 0.4s, background-color 1.2s;").find('small').attr("style","left: "+l[c]+"; transition: background-color 0.4s, left 0.2s; background-color: rgb(255, 255, 255);");
}else if ( check.checked && !active ){
$(check).prop("checked",false).next('span').attr("style","box-shadow: rgb(223, 223, 223) 0px 0px 0px 0px inset; border-color: rgb(223, 223, 223); background-color: rgb(255, 255, 255); transition: border 0.4s, box-shadow 0.4s;").find('small').attr("style","left: 0px; transition: background-color 0.4s, left 0.2s;");
}
}
changeSwitch(".js-switch",true);
If you try this to reset form, use it before:
changeSwitch(".js-switch",true);
$("#frm_id").trigger("reset");
Combined a few answers, works with v0.8.2.
function setSwitchery(switchElement, checkedBool) {
if (checkedBool && !switchElement.checked) { // switch on if not on
$(switchElement).trigger('click').attr("checked", "checked");
} else if (!checkedBool && switchElement.checked) { // switch off if not off
$(switchElement).trigger('click').removeAttr("checked");
}
}
Example usage:
var switchElement = $('#mySwitchInput');
setSwitchery(switchElement, false);
I found the solution from native github issue tracker link. Here is the working example: http://jsfiddle.net/3am89/
This is the piece of code you need to add in and manually call this function to re-render the button:
function onChange(el) {
if (typeof Event === 'function' || !document.fireEvent) {
var event = document.createEvent('HTMLEvents');
event.initEvent('change', true, true);
el.dispatchEvent(event);
} else {
el.fireEvent('onchange');
}
}
The issue that describes this scenoario is
https://github.com/abpetkov/switchery/issues/27
If you are using the switches with Bootstrap collapse, programmatically setting the state fails to expand the data-target every second time. Timing issues with the click handler I assume. This makes it work
function setSwitchery(switchElement, checkedBool) {
if (checkedBool && !switchElement.checked) { // switch on if not on
$(switchElement).trigger('click').prop("checked", false);
// make sure the data target shows
$($(switchElement).data('target')).addClass('show');
} else if (!checkedBool && switchElement.checked) { // switch off if not off
$(switchElement).trigger('click').prop("checked", false);
$($(switchElement).data('target')).removeClass('show');
}
}
If the $('#sound-active-input').click() did not work you, you can try triggering a click on the span that switchery creates after the checkbox.
$('#sound-active-input').next('span').click();
That was the only way it worked for me. Hope it helps.
My answer: because I don't want to trigger the change event that will execute a defined function
var myCheckbox = $("id_your_checkbox")
// your new value true or false
myCheckbox.checked = true;
//remove the old switchery
$('#' + myCheckbox.id).siblings("span.switchery").remove();
//and recreate the switchery
new Switchery(document.querySelector('#' + myCheckbox.getAttribute('id') + ''), {
color: '#1abc9c',
jackColor: '#fff'
});
$('selector').click(function () {
$("selector").toggle(this.checked);
});
if you are using jquery version <1.6
use this
$('#checkMeOut').attr('checked');
I am not sure if you found a solution to this problem, as I too had the same problem and after reading through your discussion with #Rickdep, though he was not able to help you (even though the solution he posted has a check next to it), you guys did point me in the right direction and I was able to come up with a solution, so thank you. Anyway, here is the solution I came up with.
First, you need to be using the class set on the span element you're generating with switchery.js, on your $('.class').click(); function: so for example, the span being generating in my solution looks as such:
<span class="switcher-questionnaire" style="border-color: rgb(121, 186, 97); box-shadow: rgb(121, 186, 97) 0px 0px 0px 16px inset; transition: border 0.7s, box-shadow 0.7s, background-color 2.0999999999999996s; -webkit-transition: border 0.7s, box-shadow 0.7s, background-color 2.0999999999999996s; background-color: rgb(121, 186, 97);">
<small style="left: 50px; transition: left 0.35s; -webkit-transition: left 0.35s;"></small>
</span>
Since the class I am telling switchery.js to generate in this solution is "switcher-questionnaire", that is the class I want to use in my click function, which looks like this:
$('.switcher-questionnaire').click( function() {
if ($(this).children('small').css("left") === '50px') {
$('.questionnaire-overlay').show();
} else {
$('.questionnaire-overlay').hide();
}
console.log('Clicked');
});
For my solution, I wanted to be able to use the switch to hide and show an overlay layer that disables access to specified content the user is viewing if the user determines the section 'does not apply'. Since switchery.js hides the checkbox and replaces that checkbox with a span that creates the Apple-esque switch we all want, but since switchery.js does not actually change the checked/unchecked state of the hidden checkbox, you are unable to use a boolean statement that is actively validating against the checkbox 'checked' attribute. This being the case, I most significant change I noticed the switch does when being toggled is changing the left position of the 'small' element from 50px to 0px when it is clicked:
<small style="left: 50px; transition: left 0.35s; -webkit-transition: left 0.35s;"></small>
I chose this as what I would use as a boolean solution to check against with a little bit of jQuery's magical sauce.
I am pretty much a noob when it comes to programming, but I felt it would be helpful if I explained some of my thought process when solving this problem.
For the AngularJS version, the uiSwitch directive is incomplete to support this.
You must to add a $formatter for the ngModel in the uiSwitch directive that update the switcher value.
ngModel.$formatters.push(function(value) {
$timeout(function() {
ngModel.$setViewValue(value);
switcher.setPosition(value);
});
});
With this, when you update the model in your code will be reflected in the ui-switch directive.
JSFiddle demo
Please Checkit!
function changeSwitch(sltor,active) {
var check = $(sltor).get(0);
if ( (!check.checked && active) || (check.checked && !active) ){
$(check).next('span').trigger('click')
}
}
changeSwitch('.onlyOnThisDate',false);
elems.forEach(function(html) {
let switchery = new Switchery(html, {
size: 'medium',
secondaryColor: '#DC3545'
});
});
Html
<input type="checkbox" class="form-check-input-switchery radio-checkbox" id="chkId">
Javascript
new Switchery("#chkId");
chkId.element.checked = true; //true or false
chkId.handleOnchange();
Related
Faking a toggle switch with an Input Range, dealing with custom range
I need to fake a toggle switch with an input range. The idea is to create a short range, with just 2 values, min and max. the css button will match one end of the range. So far you click on it, the div containing the range will move a bit bringing the other end of the ranger under your mouse. I have this function, which applies on all input ranges on the page. But i need to apply it only on some classes, not all. But i can't find the right syntax and it doesn't work. The Javascript: $('input[type="range"]').on('change', function() { $('div#launcher01').css('margin-top', parseInt($(this).val() ) > 0 ? parseInt($(this).val() ) + 'px' : '0px'); }); CSS: .fakbl input { height: 50px; width: 50px; HTML: <div id="launcher01"> <div class="fakbl"> <input type="range" id="launch01" name="launch01" min="0" max="50" step="50"" /> </div> </div> Fiddle
Since you are already using jQuery, you can phrase your widget-maker as a jQuery plugin as follows : $.fn.rangeButton = function(containerSelector) { return this.each(function() { var $self = $(this); $self.on('change', function() { $self.closest(containerSelector).css('margin-left', ($self.val()/3) > 0 ? ($self.val()/3) + 'px' : '0px'); }).trigger('change'); // trigger 'change' immediately to initialize everything. }); }; Now, invoke the widget on each of your ranges, and pass a selector for the appropriate container : $('#launcher01 input[type="range"]').rangeButton('#launcher01'); $('#launcher02 input[type="range"]').rangeButton('#launcher02'); Demo Alternatively, by giving all containers the same class, you can invoke all your widgets with a single command : $('.myClass input[type="range"]').rangeButton('.myClass'); Demo
May I ask a refinement please? I completed the fake button. As you can see in this FIDDLE (the white box will disappear, I added some opacity to it just to show that the button is working) The red box (now green due to my buggy code part) is in the background and I would need it to change color depending on the status. I tried this but it doesn't work. Here the code: $.fn.rangeButton = function(containerSelector) { return this.each(function() { var $self = $(this); $self.on('change', function() { $self.closest(containerSelector).css('margin-left', ($self.val()/3) > 0 ? ($self.val()/3) + 'px' : '0px'); // this part is not working, if you remove this part, the button works flawlessy if ($self = 100) { document.getElementById("fakbuttonsfondo01").style.backgroundColor="rgb(0, 191, 1)"; } else { document.getElementById("fakbuttonsfondo01").style.backgroundColor="rgb(0, 0, 255)"; } // end of buggy code }).trigger('change'); // trigger 'change' immediately to initialize everything. }); }; $('#launcher01 input[type="range"]').rangeButton('#launcher01'); $('#launcher02 input[type="range"]').rangeButton('#launcher02'); Thanks:)
Detect page find/search to expand a collapsible
My team is using an expandable box to condense info on our wiki (in Confluence), it's pretty standard using display:none/block. I'd like this to work with the browser's find functionality. I've found that when I switch to hiding the content using max-height the browser at least finds the text correctly, but I'd like to expand the collapsible when a match is found inside it and re-collapse it when find is no longer looking at it. Is there a way to do that? I've already tried the focus and selectionchange events to no avail. I guess I could track scrolling for jumps or track keystrokes but neither of those really tells me if the collapsible is where the query was found. tl;dr is there a way to detect browser find? Update: Here's an idea of what the code looks like: var expand = document.querySelector('.expand'); expand.querySelector('.head').addEventListener('click', function(e) { //toggle a class .show on .expand }) And my CSS: .expand .body { opacity: 0; max-height: 0; padding: 0 20px 0 40px; transition: all .4s; } .expand.show .body { max-height: 3000px; opacity: 1; padding: 10px 20px 20px 40px; }
Actually you can detect key press combination such as Ctrl+F like below var map = {17: false, 70: false}; $(document).keydown(function(e) { if (e.keyCode in map) { map[e.keyCode] = true; if (map[17] && map[70]){ // FIRE EVENT YOU EVENT } } }).keyup(function(e) { if (e.keyCode in map) { map[e.keyCode] = false; } });
JQuery or Javascript that will make an element fade away automatically
So I am making a clicker game and am kind of stuck. I want a popup like cookieClicker has when you get an achievement. It pops up and tells you what happened, you can click the x or it will just fade away after a few seconds. I tried making something with pure javascript and CSS to no avail, it would fade away nicely but not automatically. So how do I make it so whenever X element is made/displayed then it goes away after 3 seconds? Also, if it matters the element would be created by a javascript function, and multiples might be created at the same time. P.S. I tried searching and found something about auto-fading in javascript but nothing in there seemed to work either. EDIT: After trying to view cookieclicker source and playing the game again it appears it doesn't even have this functionality. The closest thing I can compare it to is when you would add something to your cart on a website, then it alerts you the item was added and then fades away.
Here is one approach which uses Javascript to trigger a CSS transition: var button = document.getElementsByTagName('button')[0]; var div = document.getElementsByTagName('div')[0]; function autoFader() { if (window.getComputedStyle(div).getPropertyValue('display') === 'none') { div.style.display = 'block'; setTimeout(function(){ div.style.opacity = '0'; },10); setTimeout(function(){ div.removeAttribute('style'); },4010); } } button.addEventListener('click',autoFader,false); div { display: none; width: 200px; height: 100px; margin: 20px auto; padding: 6px; font-size: 20px; color: rgb(255,255,255); text-align: center; border: 3px solid rgb(127,0,0); background-color: rgb(255,0,0); opacity: 1; transition: opacity 3s linear 1s; } <button type="button">Click Me</button> <div> <p>Hi, I'm an auto-fading pop-up.</p> </div>
So, your openPopup function might look like this: function openPopup(/* options here */) { const popup = actuallyOpenPopup(); waitSomeTimeAndCloseIfNotClosedYet(popup); } where 2nd function should take a popup instance (which has .close method probably, or dismiss) and start a timeout. You need to keep that timeout, so if close was called, you need to cancel it. Something like this: function waitSomeTimeAndCloseIfNotClosedYet(popup) { const originalClose = popup.close; /* monkey patching, decorating, separate method - whatever you prefer */ popup.close = function () { clearTimeout(this.timeout); originalClose.call(this); }; popup.timeout = setTimeout(() => popup.close(), 3000); } So, if was closed manually - it wont be called twice, if not, will fire up a timeout and close automatically. Via CSS you can only achieve visible closing, but not removal of nodes. (Google for transition visibility, fade out modal etc.) Hope this helps!
Toggling between two different Opacities
I have all 26 letters in the alphabet and I want to make it so that when you click on it will fade to a lower opacity but if you click on it again it will come back to 1.0 opacity. I have not a single clue on how I would go about specifically choosing the letter that was clicked on and I also cant seem to figure out how I would toggle it to a specific opacity. $(document).ready(function() { $(".alphabetLetter").click(function(event) { var x = event.target||event.srcElement; if(event.target.style.opacity == 1.0){ $(x).fadeTo('slow',0.5); } else if(event.target.style.opacity == 0.5){ $(x).fadeTo('slow',1.0); } }); });
You can select for the currently clicked element by using $(this) inside the click event handler. $(document).ready(function() { $(".alphabetLetter").click(function(event) { if ($(this).css('opacity') == '1') $(this).animate({'opacity':0}) else $(this).animate({'opacity':1}) }); });
Here's a full simple example: HTML: <p class="alphabet">abcdefghijklmnopqrstuvwxyz</p> JavaScript: // Your container var $wrap = $('p.alphabet'); // Wrap all letters in <span> $wrap.html(function(){ return $(this).text().replace(/./g, '<span class="letter">$&</span>'); }); // Attach the event $wrap.find('.letter').click(function(){ var isHidden = $(this).css('opacity') == .5; $(this).fadeTo(300, isHidden ? 1 : .5); }); Demo: http://jsbin.com/eyajel/1/edit
The opacity can just be done with css transitions and regular old styles. The CSS .letter { transition: opacity 1s; color: red; cursor: pointer; } .letter.active { opacity: 0.2; } The Javascript $('body').on('click', '.letter', function(e){ $(this).toggleClass('active'); }); Here is a JSFiddle as an example. It also includes a way to take a string of letters and turn them into markup that works with this: http://jsfiddle.net/PFjnB/1/
How to disable all div content
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>