in another question on SO, I was determining how to toggle off a function, and the working solution is this:
I place var disabledFlag = true;
in the head section of my page and before calling shell.js, then in shell.js I have:
/*******************************/
/* TOGGLE BUTTON
/*******************************/
var toggleBlock = function() {
console.log(disabledFlag);
if(!disabledFlag){
var windowsize = $(window).width(),
isDesktop = windowsize > 765;
$("#quicksearch").toggleClass("collapse in", isDesktop);
$("#quicksearch").toggleClass("collapse out", !isDesktop);
$("#sidebar").toggleClass("collapse in", isDesktop);
$("#sidebar").toggleClass("collapse out", !isDesktop);
}
else {
$("#quicksearch").addClass("collapse out");
$("#sidebar").addClass("collapse out");
}
}
$(document).ready(toggleBlock);
$(window).on("resize.showContent", toggleBlock);
toggleBlock();
shell.js is an common file that is shared with other sites and may not have the variable defined. how do I check if the variable is defined, and if not assign it to false and then execute the code above?
try
if (typeof disabledFlag === 'undefined')
disabledFlag = false;
There are easier ways to do it than using ternaries or if else
statements.
As far as your specific function goes, you could do something like this:
var toggleBlock = function() {
var disabledFlag = disabledFlag||false;
if(!disabledFlag){
//etc.
undefined
is falsy, so it works with the logical ||
operator. That ||
operator makes the new var disabledFlag
be set to disabledFlag
(if it exists), and if not, it will set the var
to false
This same concept is used in many different contexts. For example:
Situation 1 -
var obj = {hello: 'world'};
function fn(object) {
var object = object || {foo: 'bar'};
return object;
}
fn(obj) // ==> {hello: 'world'}
Situation 2 -
function fn(object) {
var object = object || {foo: 'bar'};
return object;
}
fn(objectThatDoesntExist); // ==> {foo: 'bar'}
In JavaScript libraries and module-pattern projects, this concept is used quite frequently in many different ways.
You don't need typeof
if (window.disabledFlag === undefined) window.disabledFlag = false;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With