How to make this code compatible with firefox browser - javascript

I have a question about multi browser compatibility. I want to use the event.target instead event.srcElement in the following code to make it work for firefox.
I have used target = event.target || event.srcElement. It is not working. Any help will be appreciated.
function jumptoPopupMenuItem(theMenuID)
{
if (event.srcElement.className == "RightClickMenuItems")
{
if (event.srcElement.getAttribute("url") != null)
{
var strParameters = "";
if (theMenuID == "mnuAppointmentMenu")
{
strParameters = "AppointmentNumber=" + m_strAppointmentTypeYearNumber;
}
else if (theMenuID == "mnuAvailableHourMenu")
{
strParameters = "PreFillLanguageID=" + m_nLanguageID;
strParameters = strParameters + "&PreFillInterpreterID=" + m_nInterpreterID;
strParameters = strParameters + "&PreFillDateOfService=" + m_dtDateOfService;
}
if (event.srcElement.getAttribute("target") != null)
{
var PopupWindow = window.open(
event.srcElement.url + strParameters,
event.srcElement.getAttribute("target"));
PopupWindow.focus();
}
else
{
window.location = event.srcElement.url;
}
}
hidePopupMenu(theMenuID);
}
}

Some standard ways to register event handlers with compatibility (very simplified code):
HTML:
<button onclick="eventHandlerFunc(event)" />
<!-- better to register as: -->
<button onclick="eventHandlerFunc.call(this,event)" />
JavaScript (addEventListener or attachEvent):
if (window.addEventListener) someElem.addEventListener("click",eventHandlerFunc,false);
else if (window.attachEvent) someElem.attachEvent("onclick",eventHandlerFunc);
JavaScript (element property):
someElem.onclick = eventHandlerFunc;
Where eventHandlerFunc() function defined as:
function eventHandlerFunc(event) { // or var eventHandlerFunc = function(event) {
event = event||window.event; // can be needed only for IE6-IE8
// because `event` parameter hide `event` global
// variable (`window.event`)
var target = event.target||event.srcElement
}
NOTE: If needed compatibility for this variable additional code must be added.
If then needed to use event variable (defined inside eventHandlerFunc() as parameter) inside other functions you must send it to these functions:
function eventHandlerFunc(event) {
event = event||window.event; // can be needed only for IE6-IE8
/*
...
*/
jumptoPopupMenuItem(event,theMenuID);
}
function jumptoPopupMenuItem(event,theMenuID) {
}

Related

jQuery script works only once, then TypeError: $(...) is not a function

I've downloaded this script for use conditional fields in forms:
(function ($) {
$.fn.conditionize = function(options) {
var settings = $.extend({
hideJS: true
}, options );
$.fn.showOrHide = function(is_met, $section) {
if (is_met) {
$section.slideDown();
}
else {
$section.slideUp();
$section.find('select, input').each(function(){
if ( ($(this).attr('type')=='radio') || ($(this).attr('type')=='checkbox') ) {
$(this).prop('checked', false).trigger('change');
}
else{
$(this).val('').trigger('change');
}
});
}
}
return this.each( function() {
var $section = $(this);
var cond = $(this).data('condition');
// First get all (distinct) used field/inputs
var re = /(#?\w+)/ig;
var match = re.exec(cond);
var inputs = {}, e = "", name ="";
while(match !== null) {
name = match[1];
e = (name.substring(0,1)=='#' ? name : "[name=" + name + "]");
if ( $(e).length && ! (name in inputs) ) {
inputs[name] = e;
}
match = re.exec(cond);
}
// Replace fields names/ids by $().val()
for (name in inputs) {
e = inputs[name];
tmp_re = new RegExp("(" + name + ")\\b","g")
if ( ($(e).attr('type')=='radio') || ($(e).attr('type')=='checkbox') ) {
cond = cond.replace(tmp_re,"$('" + e + ":checked').val()");
}
else {
cond = cond.replace(tmp_re,"$('" + e + "').val()");
}
}
//Set up event listeners
for (name in inputs) {
$(inputs[name]).on('change', function() {
$.fn.showOrHide(eval(cond), $section);
});
}
//If setting was chosen, hide everything first...
if (settings.hideJS) {
$(this).hide();
}
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}(jQuery));
I'm trying this because I need to use conditionize() in one of my tabs and when I reload the tab, all works but if I go to other tab and I return to the previous tab(where I need this works), I get that error.
When I change tabs, I'm only reloading one part of the page.
When I load the page this works perfectly, but if I try to call function again from browser console, it tells me that TypeError: $(...)conditionize() is not a function.
I have included the script in header tag and I'm calling it with this script on the bottom of body:
<script type="text/javascript">
$('.conditional').conditionize();
</script>
EDIT:
I have written
<script type="text/javascript">
console.log($('.conditional').conditionize);
setTimeout(function () {console.log($('.conditional').conditionize);}, 2);
</script>
and this print me at console the function, and when 2 milliseconds have passed, it print me undefined
I have found the solution.
Because any reason, the $ object and jQuery object are not the same in my code.
I have discovered it using this on browser console:
$===jQuery
This return false (This was produced because in other JS, I was using the noConflict(), which give me the problem)
Explanation: noConflict()
So I have solved it changing the last line of my JS by:
//Show based on current value on page load
$.fn.showOrHide(eval(cond), $section);
});
}
}($));
Putting the $ instead of 'jQuery'

Using JQuery on a window reference?

Can you use JQuery on a window reference? I have tried the following with no luck.
function GetDiPSWindow() {
var DiPSURL = "/DiPS/index";
var DiPSWindow = window.open("", "DiPS", "toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=no,width=520,height=875");
if (DiPSWindow.location.href === "about:blank") {
DiPSWindow.location = DiPSURL;
}
return DiPSWindow;
}
function AddRecipient(field, nameId) {
// Get window
var win = GetDiPSWindow();
// Attempt 1
$(win.document).ready(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
// Attempt 2
$(win).ready(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
// Attempt 3
$(win).load(function () {
var input = win.document.getElementById(field + "_Input");
input.value = nameId;
});
}
Am I making a simple mistake?
EDIT For some reason, win.document.readyState is "complete". Not sure if that makes a difference.
I have also tried:
View contains:
<script>var CallbackFunction = function() {}; // Placeholder</script>
The method:
function AddRecipient(field, nameId) {
var DiPSURL = "/DiPS/index";
if (deliveryChannel === undefined) {
deliveryChannel = 0;
}
var DiPSWindow = GetDiPSWindow();
if (DiPSWindow.location.href === "about:blank") {
DiPSWindow.location = DiPSURL;
DiPSWindow.onload = function () { DiPSWindow.CallbackFunction = AddRecipient(field, nameId) }
} else {
var input = DiPSWindow.document.getElementById(field + "_Input");
input.value = input.value + nameId;
var event = new Event('change');
input.dispatchEvent(event);
}
}
The answer is.... kinda. it depends on what you are doing.
You can use jquery on the parent page to interact with a page within an iframe, however, anything that requires working with the iframe's document object may not work properly because jQuery keeps a reference of the document it was included on and uses it in various places, including when using document ready handlers. So, you can't bind to the document ready handler of the iframe, however you can bind other event handlers, and you can listen for the iframe's load event to know when it is absolutely safe to interact with it's document.
It would be easier though to just include jquery within the iframe itself and use it instead. It should be cached anyway, so there's no real detriment to performance by doing so.

Force line to execute before closure

I have the following code
(function() {
var weather = new Weather();
var input = document.getElementById("inputCity");
var weatherHolder = document.getElementsByClassName("weather");
var loading = document.getElementById("loadingSign");
input.focus();
input.onkeyup = function(e) {
if (e.keyCode == 13 && input.value != "") {
loading.classList.remove("hidden");
weather.getWeather(input.value, function (returnValue) {
for (iter in returnValue) {
weatherHolder[iter].classList.remove('hidden');
document.getElementById("weather" + (parseInt(iter) + 1)).innerHTML = returnValue[iter].date;
}
});
loading.classList.add("hidden");
}
};
})();
I want to force the execution of the line loading.classList.remove("hidden"); before waiting for the closure bellow to complete.
If I remove the closure lines the script works perfectly, however, I can't make it work if the closure fails.
For instance, the code below works perfectly:
(function() {
var weather = new Weather();
var input = document.getElementById("inputCity");
var weatherHolder = document.getElementsByClassName("weather");
var loading = document.getElementById("loadingSign");
input.focus();
input.onkeyup = function(e) {
if (e.keyCode == 13 && input.value != "") {
loading.classList.remove("hidden");
alert("teste");
loading.classList.add("hidden");
}
};
})();
The problem is in the line loading.classList.remove("hidden"); . This is supposed to remove a class that's hiding a message and a spinner. If I replace the closure lines with an alert the spinner shows, however, if I have that closure function the spinner is never shown.
How can I force that line to be called whether the closure is successful or not?
I don't really understand the question but judging from the code you have, it would be wiser to add the loading.classList.add("hidden"); inside the callback so it gets executed correctly.
(function() {
var weather = new Weather();
var input = document.getElementById("inputCity");
var weatherHolder = document.getElementsByClassName("weather");
var loading = document.getElementById("loadingSign");
input.focus();
input.onkeyup = function(e) {
if (e.keyCode == 13 && input.value != "") {
loading.classList.remove("hidden");
weather.getWeather(input.value, function (returnValue) {
for (iter in returnValue) {
weatherHolder[iter].classList.remove('hidden');
document.getElementById("weather" + (parseInt(iter) + 1)).innerHTML = returnValue[iter].date;
}
// Here
loading.classList.add("hidden");
});
}
};
})();
Ok so you are asking to "force the execution of..." but in fact what I suspect is happening here is that: the line we moved was not "waiting" on getWeather to finish.

Javascript help - combo box

Hi I need some help understanding this code:
It works well but can someone add some comments to help me understand it better?
Thanks
Here's the code:
function contractall() {
if (document.getElementById) {
var inc = 0
while (document.getElementById("dropmsg" + inc)) {
document.getElementById("dropmsg" + inc).style.display = "none"
inc++
}
}
}
function expandone() {
if (document.getElementById) {
var selectedItem = document.dropmsgform.dropmsgoption.selectedIndex
contractall()
document.getElementById("dropmsg" + selectedItem).style.display = "block"
}
}
if (window.addEventListener) window.addEventListener("load", expandone, false)
else if (window.attachEvent) window.attachEvent("onload", expandone)
The function contract all finds all the elements with the id of dropmsg0, dropmsg1 ... dropmsgN
and hides them. The function expanddone shows the selected element. This is done by setting the style on
the elements.
The last 2 lines are an incomplete attempt at browser comparability.
It would work in more browsers if a cross browser library like jQuery were used.
function contractall() {
if (document.getElementById) {
var inc = 0; // counter
// loop on all dropmsg in the document
while (document.getElementById("dropmsg" + inc)) {
// hide one by one
document.getElementById("dropmsg" + inc).style.display = "none"
inc++
}
}
}
function expandone() {
if (document.getElementById) {
var selectedItem = document.dropmsgform.dropmsgoption.selectedIndex; // get the selected item
contractall() // hide all in the document
// show the selected item
document.getElementById("dropmsg" + selectedItem).style.display = "block"
}
}
// add event handlers to windows load.
if (window.addEventListener) window.addEventListener("load", expandone, false)
else if (window.attachEvent) window.attachEvent("onload", expandone)

Class methods as event handlers in JavaScript?

Is there a best-practice or common way in JavaScript to have class members as event handlers?
Consider the following simple example:
<head>
<script language="javascript" type="text/javascript">
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked;
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
</script>
</head>
<body>
<input type="button" id="btn1" value="Click me" />
<script language="javascript" type="text/javascript">
var btn1counter = new ClickCounter('btn1');
</script>
</body>
The event handler buttonClicked gets called, but the _clickCount member is inaccessible, or this points to some other object.
Any good tips/articles/resources about this kind of problems?
ClickCounter = function(buttonId) {
this._clickCount = 0;
var that = this;
document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
EDIT almost 10 years later, with ES6, arrow functions and class properties
class ClickCounter {
count = 0;
constructor( buttonId ){
document.getElementById(buttonId)
.addEventListener( "click", this.buttonClicked );
}
buttonClicked = e => {
this.count += 1;
console.log(`clicked ${this.count} times`);
}
}
https://codepen.io/anon/pen/zaYvqq
I don't know why Function.prototype.bind wasn't mentioned here yet. So I'll just leave this here ;)
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.buttonClicked.bind(this);
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount + ' times');
}
}
A function attached directly to the onclick property will have the execution context's this property pointing at the element.
When you need to an element event to run against a specific instance of an object (a la a delegate in .NET) then you'll need a closure:-
function MyClass() {this.count = 0;}
MyClass.prototype.onclickHandler = function(target)
{
// use target when you need values from the object that had the handler attached
this.count++;
}
MyClass.prototype.attachOnclick = function(elem)
{
var self = this;
elem.onclick = function() {self.onclickHandler(this); }
elem = null; //prevents memleak
}
var o = new MyClass();
o.attachOnclick(document.getElementById('divThing'))
You can use fat-arrow syntax, which binds to the lexical scope of the function
function doIt() {
this.f = () => {
console.log("f called ok");
this.g();
}
this.g = () => {
console.log("g called ok");
}
}
After that you can try
var n = new doIt();
setTimeout(n.f,1000);
You can try it on babel or if your browser supports ES6 on jsFiddle.
Unfortunately the ES6 Class -syntax does not seem to allow creating function lexically binded to this. I personally think it might as well do that. EDIT: There seems to be experimental ES7 feature to allow it.
I like to use unnamed functions, just implemented a navigation Class which handles this correctly:
this.navToggle.addEventListener('click', () => this.toggleNav() );
then this.toggleNav() can be just a function in the Class.
I know I used to call a named function but it can be any code you put in between like this :
this.navToggle.addEventListener('click', () => { [any code] } );
Because of the arrow you pass the this instance and can use it there.
Pawel had a little different convention but I think its better to use functions because the naming conventions for Classes and Methods in it is the way to go :-)

Categories

Resources