views:

160

answers:

2

I read this article regarding creating popup notes with javascript and css

The problem is that this one works only in IE since window.event is undefined in Firefox.

// assigns X,Y mouse coordinates to note element
note.style.left=event.clientX;
note.style.top=event.clientY;

So could you point me a fully working example? Or at least, how could i modify the javascript code to make it work in both internet browsers?

+2  A: 

There are more than two browsers, but the following should work in most of them (adapted from the function on the page you linked to):

showNote = function(evt) {
    evt = evt || window.event;
    // gets note1 element
    var note1=document.getElementById('note1');
    // assigns X,Y mouse coordinates to 'note1' element
    note1.style.left=evt.clientX;
    note1.style.top=evt.clientY;
    // makes note1 element visible
    note1.style.visibility='visible';
};

The problem is that not all browsers have an event property of window and instead use an event object implicitly passed in as a parameter to an event handler function such as showNote. The evt = evt || window.event; line assigns window.event to the evt variable if no event parameter was passed into the function (which is what happens in Internet Explorer).

Tim Down
A: 

You can separate the two branches when you define the method. It takes more characters than bundling them together, but you do not have to check for support on every every call.

//

window.whereAt= (function(){
    var fun;
    if(typeof pageXOffset== 'number'){
        fun= function(e){
            var pX, pY, sX, sY;

            pX= e.clientX || 0;
            pY= e.clientY || 0;
            sX= window.pageXOffset;
            sY= window.pageYOffset;
            return [(pX+sX), (pY+sY)];
        }
    }
    else{
        fun= function(e){
            e= (e && e.clientX)? e: window.event;
            var pX, pY, sX, sY;

            pX= (e.clientX);
            pY= (e.clientY);
            var d= document.documentElement;
            var b= document.body;
            sX= Math.max(d.scrollLeft, b.scrollLeft);
            sY= Math.max(d.scrollTop, b.scrollTop);
            var pwot= [(pX+sX), (pY+sY)];
            return pwot;
        }
    }
    return fun;
})()
//test case
document.ondblclick= function(ev){
    alert(whereAt(ev))
};
kennebec