Remove javascript function override - javascript

I have a java script function override that occurs when certain condition is met. How can I reset these functions to its original state if I don't need it anymore.
function setProductFields() {
if (shouldShow == 'true') {
selectField = function() {
//override
}
} else {
selectField() <--- //return to its original state
}
}

Save a reference to the old selectField in a variable, prior to changing it:
var oldSelectField = selectField;
// ... other code ...
function setProductFields() {
if (shouldShow == 'true') {
selectField = function() {
//override
}
} else {
selectField = oldSelectField;
}
}

Related

Function is not calling the correct function

I want to save a bool value for when you refresh the page, the value is true (if you want the color theme to be default, white) and false (if you want the color theme to be dark, black). Local storage is saving the last value correctly, and loading the correct value, but it is still not working, I don't know why. Here is my code, any help would be grateful.
var link = document.getElementById("color-mode");
var button = document.getElementById("theme-button");
var searchButton = document.getElementById("search-button");
var userSettings = document.getElementById("user-settings");
var siteLogo = document.getElementById("site-logo");
var isDefault = false;
button.onclick = function() {
if(isDefault == true) {
DarkTheme();
}
else {
DefaultTheme();
}
}
function DefaultTheme() {
link.href = "../static/CSS/default.css";
isDefault = true;
searchButton.src = "../static/Media/SearchIconDefault.png";
userSettings.src = "../static/Media/UserIconDefault.png";
siteLogo.src = "../static/Media/LogoDefault.png";
window.localStorage.setItem("saveTheme", isDefault);
}
function DarkTheme() {
link.href = "../static/CSS/dark.css";
isDefault = false;
searchButton.src = "../static/Media/SearchIconDark.png";
userSettings.src = "../static/Media/UserIconDark.png";
siteLogo.src = "../static/Media/LogoDark.png";
window.localStorage.setItem("saveTheme", isDefault);
}
function load() {
isDefault = window.localStorage.getItem("saveTheme");
console.log("Val: " + isDefault);
if(isDefault == false) {
DarkTheme();
}
else {
DefaultTheme();
}
}
load();
Read your code:
load() initially had isDefault as false
it calls DarkTheme, which sets isDefault also to false
then user click button
isDefault is false - then DarkTheme is called, which test isDefault also to false.
Application basically can't enter other theme, except the case where you change something manually in localStorage.
Change code to :
button.onclick = function() {
if(isDefault == true) {
DefaultTheme();
}
else {
DarkTheme();
}
}

jQuery, on input[type=radio] change verify something if false, call 2 other functions

I am trying to create an event that fires some functions depending on the id of an input[type=radio]. If the Id clicked is different to maybe_evtDiag, it should call this.applySubConditionalRequired(); and this.bindUISubActions();. Why is my code not working?
var SubFormStuff = {
init: function()
this.applySubConditionalRequired();
this.bindUISubActions();
},
bindUISubActions: function() {
// when a radio or checkbox changes value, click or otherwise
$("input[type='radio'].stepThreeDiag").change(function() {
if($(this).attr("id") == "maybe_evtDiag") {
$(this).prop('checked', false);
}else{
//this is not working //
applySubConditionalRequired(this);
displaySubFormRequired(this);
}
});
},
applySubConditionalRequired: function() {
$(".require-if-subevent-active").each(function() {
var el = $(this);
// does something
});
},
displaySubFormRequired: function() {
$(".div-subevent-class").each(function() {
var el = $(this);
// does something else
});
}
};
SubFormStuff.init();
Like you did in the init(), add a reference to the object (this) to call a sibling function (not to lose the context):
bindUISubActions: function() {
var _SubFormStuff = this;
// when a radio or checkbox changes value, click or otherwise
$("input[type='radio'].stepThreeDiag").change(function() {
if($(this).attr("id") == "maybe_evtDiag") {
$(this).prop('checked', false);
} else{
_SubFormStuff.applySubConditionalRequired();
_SubFormStuff.displaySubFormRequired();
}
});
More details on scope and context in JavaScript
You should call the methods like this:
bindUISubActions: function() {
// Store the reference to the current object
var self = this;
// when a radio or checkbox changes value, click or otherwise
$("input[type='radio'].stepThreeDiag").change(function() {
if($(this).attr("id") == "maybe_evtDiag") {
$(this).prop('checked', false);
} else{
self.applySubConditionalRequired();
self.displaySubFormRequired();
}
});
}
This way you can assing to self the current scope, and use it later on any other function call in the same execution scope.
More about javascript scope
You are trying to call applySubConditionalRequired(this) and displaySubFormRequired(this) in the wrong context you should get applySubConditionalRequired and displaySubFormRequired are not defined.
Try this:
bindUISubActions: function() {
// when a radio or checkbox changes value, click or otherwise
var that = this;
$("input[type='radio'].stepThreeDiag").change(function() {
if($(this).attr("id") == "maybe_evtDiag") {
$(this).prop('checked', false);
}else{
//it should work now //
that.applySubConditionalRequired(this);
that.displaySubFormRequired(this);
}
});
},

Hiding and Showing default javascript alert

How to hide and show the default Javascript alert in the same HTML Page.
For example:
In function_one I want to hide the Javascript default alert
function function_one() {
//hide Javascript alert
}
In function_two I want to show the default Javascript which has been hidden in function_one
function function_two() {
//show Javascript alert
}
Both Javascript functions are in the same HTML page.
If you want to prevent calls to alert() from being displayed, use the following code:
var defaultAlert = null;
function function_one() {
if (defaultAlert === null) {
defaultAlert = window.alert;
window.alert = function() {};
}
}
function function_two() {
if (defaultAlert !== null) {
window.alert = defaultAlert;
defaultAlert = null;
}
}
You can disable it by overriding its value with an empty function. You store the old value in a variable (oldAlert) and then restore it assigning the old value back to window.alert:
function function_one() {
oldAlert = window.alert;
window.alert = function() {};
}
function function_two() {
window.alert = oldAlert;
}

How to use this piece of code in a function

I have this jQuery code:
var vis = (function(){
var stateKey, eventKey, keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
break;
}
}
return function(c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];
}
})();
vis(function(){
document.title = vis() ? 'Visible' : 'Not visible';
});
What it does now is to change the document title of the page. If the page is not visible, it will be changed to that and vise verca.
My question is, how can I use this function like this:
if page is visible{
//do something
}
if page is not visible{
//do something else
}
Your vis() function is binding an event handler when it's passed one, otherwise returning the status. Thus:
vis(function(event) {
if ( vis() ) {
// visible
} else {
// not visible
}
});
Or more verbosely:
var handler = function(){
// calling vis() with no arguments will return a boolean
if (vis()) {
// visible
} else {
// not visible
}
}
// if a handler is passed, it gets bound to the event
// thus, runs on *any* visibility state change
vis(handler);

How do I add a function to an element via jQuery?

I want to do something like this:
$('.dynamicHtmlForm').validate = function() {
return true;
}
$('.dynamicHtmlForm .saveButton').click(function() {
if (!$(this).closest('.dynamicHtmlForm').validate()) {
return false;
}
return true;
});
And then when I have a form of class dynamicHtmlForm, I want to be able to provide a custom validate() function:
$('#myDynamicHtmlForm').validate = function() {
// do some validation
if (there are errors) {
return false;
}
return true;
}
But I get this when I do this:
$(this).closest(".dynamicHtmlForm").validate is not a function
Is what I've described even possible? If so, what am I doing wrong?
Yes, it is technically possible. You will need to reference the element itself, however, and not the jQuery collection. This should work:
$('.dynamicHtmlForm').each(function (ix,o) {
o.validate = function() {
return true;
}
});
$('.dynamicHtmlForm .saveButton').click(function() {
if ($(this).closest('.dynamicHtmlForm')[0].validate()) {
return false;
}
return true;
}
jQuery.fn.validate = function(options) {
var defaults = {
validateOPtions1 : '',
validateOPtions2 : ''
};
var settings = $.extend({}, defaults, options);
return this.each(function() {
// you validation code goes here
});
};
$(document).ready(function() {
$('selector').click(function() {
$('some selector').validate();
// or if you used any options in your code that you
// want the user to enter. then you go :
$('some selector').validate({
validateOPtions1: 'value1',
validateOPtions2: 'value2'
});
});
});
You're not adding the function to the element, you're adding it to the jQuery wrapper around the element. Every time you pass a selector to jQuery, it will create a new wrapper for the found elements:
$('#myEl'); // gives a jQuery wrapper object
$('#myEl'); // creates another jQuery wrapper object
If you save the wrapped element to a variable and use that later, it would be a different story because you're accessing the saved jQuery wrapper object.
var dynamicHtmlForm = $('.dynamicHtmlForm');
dynamicHtmlForm.validate = function() {
return true;
}
$('.dynamicHtmlForm .saveButton').click(function() {
if (dynamicHtmlForm.validate()) {
return false;
}
return true;
}
You could also add the function directly to the element using
$('.dynamicHtmlForm')[0].validate = function () { return true; }
// and later...
if (!$(this).closest('.dynamicHtmlForm')[0].validate())
Or you could look at extending jQuery properly by writing a plugin.

Categories

Resources