JavaScript script doesn't work in Firefox - javascript

I have an old function which is missing lines for Mozilla/Firefox and thus JavaScript is not working properly in it. The function tracks mouse-coordinates, so that I can position windows.
How to make the code work in Firefox as well?
Xoffset = -60; // modify these values to ...
Yoffset = 20; // change the popup position.
var old, skn, iex = (document.all),
yyy = -1000;
var ns4 = document.layers
var ns6 = document.getElementById && !document.all
var ie4 = document.all
if (ns4) skn = document.dek
else if (ns6) skn = document.getElementById("dek").style
else if (ie4) skn = document.all.dek.style
if (ns4) document.captureEvents(Event.MOUSEMOVE);
else {
skn.visibility = "visible"
skn.display = "none"
}
document.onmousemove = get_mouse;
function popup(msg, bak) {
var content =
"<TABLE WIDTH=150 BORDER=1 BORDERCOLOR=black CELLPADDING=2" +
"CELLSPACING=0 " + "BGCOLOR=" + bak + "><TD ALIGN=center>" +
"<FONT COLOR=black SIZE=2>" + msg + "</FONT></TD></TABLE>";
yyy = Yoffset;
if (ns4) {
skn.document.write(content);
skn.document.close();
skn.visibility = "visible"
}
if (ns6) {
document.getElementById("dek").innerHTML = content;
skn.display = ''
}
if (ie4) {
document.all("dek").innerHTML = content;
skn.display = ''
}
}
function get_mouse(e) {
var x = (ns4 || ns6) ? event.pageX : event.x + document.body.scrollLeft;
skn.left = x + Xoffset;
var y = (ns4 || ns6) ? event.pageY : event.y + document.body.scrollTop;
if (document.documentElement && // IE6 +4.01 but no scrolling going on
!document.documentElement.scrollTop) {
y = event.y + document.documentElement.scrollTop;
}
else if (document.documentElement && // IE6 +4.01 and user has scrolled
document.documentElement.scrollTop) {
y = event.y + document.documentElement.scrollTop;
}
else if (document.body && document.body.scrollTop) { // IE5 or DTD 3.2
y = event.y + document.document.body.scrollTop;
}
skn.top = y + yyy;
}
function kill() {
yyy = -1000;
if (ns4) {
skn.visibility = "hidden";
}
else if (ns6 || ie4) skn.display = "none"
}
I am getting this error:
"event is not defined"
Works ok in IE.

I'm not going to post code on how to rewrite your code #Ivo Wetzel's is pretty much what you need, but let meg give you some advice.
The world is changing fast, so does the computer industry. And while sometimes it's not as fast as we want (IE 6 fading slowly) there is no need to support Netscape 4.
Consult with a site like StatCounter to find out what browsers are in use (in your country/region). Also consult with YUI graded browser support. Yahoo is one of the biggest players on the internet, their site has to work for almost everyone, so they know what they're talking about.
Find a good DOM reference. MDC is pretty much what you need, but it's good to have MSDN for IE quirks. Talking about quirks, don't forget to bookmark QuirksMode compatibility tables.
Never use things like ie4 = document.all, because a single feature won't identify a whole browser. It's like saying: "Hey you've got blonde hair, you must be Brad Pitt". Use feature detection. Read these two excellent articles: Browser Detection (and What to Do Instead) and Feature Detection: State of the Art Browser Scripting
Don't use document.write because it's synchronous I/O which is awful. It blocks your page rendering and leads to bad user experience. The Web is all about being asynchronous.
"Synchronous programming is disrespectful and should not be employed in applications which are used by people." - Douglas Crockford

Oh my god... this must be the worst code I've seen in years, well let's try to clean it up then:
Xoffset = -60; // modify these values to ...
Yoffset = 20; // change the popup position.
var old, skn = document.getElementById("dek").style, yyy = -1000;
function popup(msg, bak) {
var content =
"<TABLE WIDTH=150 BORDER=1 BORDERCOLOR=black CELLPADDING=2" +
"CELLSPACING=0 " + "BGCOLOR=" + bak + "><TD ALIGN=center>" +
"<FONT COLOR=black SIZE=2>" + msg + "</FONT></TD></TABLE>";
yyy = Yoffset;
document.getElementById("dek").innerHTML = content;
skn.display = '';
}
document.onmousemove = function(e) {
e = e || window.event;
var x = e.pageX !== undefined ? e.pageX : e.clientX + document.body.scrollLeft;
var y = e.pageY !== undefined ? e.pageY : e.clientY + document.body.scrollTop;
skn.left = x + Xoffset;
skn.top = y + yyy;
}
function kill() {
yyy = -1000;
skn.display = "none";
}
It's still broken beyond repair, but it should work... somehow.... Well, unless you post the rest of them HTML there's no way I can test this.
Please, I beg you... get rid of all that crap and use jQuery.

Instead of testing for browsers, I would test to see if the object / property exists. For example:
var x = e.pageX ? e.pageX : e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
I think there may be an easier way to do this, such as
var x = e.pageX || e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
but I'm not sure that will work. Test it out and see what you get. Also, for more detail, review: quirksmode.org/js/events_properties.html
Also note that I changed "event" to "e", since the parameter you're passing into the function is "e". If you want to still use event, rewrite the parameter to:
function get_mouse(event)
While I don't believe "event" is a reserved word for JS, a lot of browsers use it, so I would suggest sticking to "e".

Looks like you need to change all your instances of 'event' to 'e'.

Firefox includes document.documentElement and document.documentElement.scrollTop and document.body and document.body.scrollTop so you're entering regions that were meant for IE with Firefox.
You should also start your function with something like
function get_mouse(e) {
e = e || window.event;
Then use e instead of event in all the places you use event.

Add var event = e on the first line of function body, if you are afraid of hassles
function get_mouse(e) { var event = e;

Related

My scroll handler JavaScript doesn't work in Internet Explorer

I have a script on my site that works in every browser, except Internet Explorer. Can someone explain why this doesn't work?
var header = document.getElementById('header');
var picturebg = document.getElementsByClassName('picturebg')[0];
var arrow = document.getElementsByClassName('toTop-transparent')[0];
var supportPageOffset = window.pageXOffset !== undefined;
window.onscroll = function() {
"use strict";
var y = window.scrollY;
if (y > 7) {
header.className = 'header-colored';
arrow.className = 'toTop';
picturebg.className = 'picturebgns';
} else {
header.className = 'header-transparent';
arrow.className = 'toTop-transparent';
picturebg.className = 'picturebg';
}
};
The console doesn't give any errors, it just doesn't work. I have another jQuery script that runs just fine.
I've seen the other question here about the same thing, but it didn't help in any way.
Certain properties used in your snippet are not supported by IE.
From the MDN page on scrollY:
For cross-browser compatibility, use window.pageYOffset instead of window.scrollY. Additionally, older versions of Internet Explorer (< 9) do not support either property and must be worked around by checking other non-standard properties.1
It appears you already have found the check for pageOffset support, so also check if non-standard properties are supported (e.g. CSS1 is compatible):
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
Try this sample, using addEventListener() instead of onscroll.
var header = document.getElementById('header');
var picturebg = document.getElementsByClassName('picturebg')[0];
var arrow = document.getElementsByClassName('toTop-transparent')[0];
var supportPageOffset = window.pageXOffset !== undefined;
var isCSS1Compat = ((document.compatMode || "") === "CSS1Compat");
header.addEventListener('scroll', function(event) {
"use strict";
var y = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop;
console.log('y: ',y);
if (y > 7) {
header.className = 'header-colored';
arrow.className = 'toTop';
picturebg.className = 'picturebgns';
} else {
header.className = 'header-transparent';
arrow.className = 'toTop-transparent';
picturebg.className = 'picturebg';
}
});
<div id="header" style="height: 50px; overflow: scroll;">
<img class="picturebg" src="https://www.gravatar.com/avatar/684fa9ff80577cbde88ffbdebafac5b4?s=32&d=identicon&r=PG&f=1" />
<div id="arrow" class="toTop-transparent">↓</div>
</div>
1https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollY#Notes

Auto minimising text in textarea with javascript

I've got a textarea where the user inputs there data, but as they add it when the cursor gets to the end it reduces the size of the font. All works quite well but I cannot seem to set a limit on how small it goes. Also is there any way I can set the point at which the text starts to go small, because the text tends to disappear at the end before shrinking? Please could someone help with this, seem to be pulling my hair out on this one?
function textAreaChange(){
var textArea1 = document.getElementById("textarea");
var sizeText1 = document.getElementById("size_text");
while (textArea1.scrollWidth > textArea1.clientWidth)
{
var fs = parseFloat(textArea1.style.fontSize) - 1;
textArea1.style.fontSize = fs + 'px';
sizeText1.value = (fs | 0) + 'px';
document.getElementById("a1").innerHTML = ((parseInt(textArea1.style.fontSize))/textboxscale);
sizeText1.value = ((parseInt(textArea1.style.fontSize))/textboxscale);
}
}
textAreaChange();
Thanks in advance.
Davetoff
Right I have added the if (fs>15) to this code, but now it lock up when it gets to 15:
function textAreaChange(){
var fss = 15;
var textArea1 = document.getElementById("textarea");
var sizeText1 = document.getElementById("size_text");
while (textArea1.scrollWidth > textArea1.clientWidth)
{
var fs = parseFloat(textArea1.style.fontSize) - 1;
if (fs >15){
textArea1.style.fontSize = fs + 'px';
sizeText1.value = (fs | 0) + 'px';
document.getElementById("a1").innerHTML = ((parseInt(textArea1.style.fontSize))/textboxscale);
sizeText1.value = ((parseInt(textArea1.style.fontSize))/textboxscale);
} else {
textArea1.style.fontSize = fss + 'px';
sizeText1.value = (fss | 0) + 'px';
document.getElementById("a1").innerHTML = fss + 'px';
}
}
}
Please help really appreciated spent a couple of days on this now and my head is beginning to hurt:
Thanks.
Davetoff
After the line where you assign "fs", just add a statement to make sure that if fs is too small, you don't assign it to the textArea1 font size, something like:
if (fs > 7) //only perform statements below if fs > 7
{
...
}
Right found the problem, indeed the answer was to add the if statement, however I was being a fool as I had a scale factor in there that was causing all sorts of problems, also I've added a keycode in there to stop additional key inputs when the end of the text area is reached, updated code below:
function textAreaChange(){
var fss = <?=$min_text_size?>*textboxscale;
var textArea1 = document.getElementById("textarea");
var sizeText1 = document.getElementById("size_text");
if (textArea1.scrollWidth > (textArea1.clientWidth))
{
var fs = parseFloat(textArea1.style.fontSize) - (2);
if (fs >(14*textboxscale)){
textArea1.style.fontSize = (fs) + 'px'; //this is the textarea style
document.getElementById("a1").innerHTML = (parseInt(textArea1.style.fontSize)/textboxscale); //this is some text to show the user what size the text is
sizeText1.value = ((parseInt(textArea1.style.fontSize))/textboxscale); //this is a slider I put to chage the text height manually (input range)
} else{
textArea1.style.fontSize = (fss) + 'px';
document.getElementById("a1").innerHTML = fss/textboxscale;
sizeText1.value = fss /textboxscale;
if (event.keyCode == 8, 32) {
event.preventDefault();
}
}
}
}
However the keycode 8,32 works well in IE but not in Firefox, any additional help would be really appreciated?
D

onnouseover not working in chrome, was working until update

I have the following function being called via onmouseover on an
function showTooltip(tip, el, evt) {
if (document.layers) {
if (!el.tip) {
el.tip = new Layer(200);
el.tip.document.open();
el.tip.document.write(tip);
el.tip.document.close();
el.onclick = function (evt) { this.tip.visibility = 'hide'; };
el.onmouseout = function (evt) { this.tip.visibility = 'hide'; };
}
el.tip.left = evt.pageX;
el.tip.top = evt.pageY;
el.tip.visibility = 'show';
}
else if (document.all) {
if (!el.tip) {
document.body.insertAdjacentHTML('beforeEnd', '<DIV ID="tip' + tc + '" CLASS="tooltip">' + tip + '<\/DIV>');
el.tip = document.all['tip' + tc++];
el.onclick = function (evt) { this.tip.style.visibility = 'hidden'; };
el.onmouseout = function (evt) { this.tip.style.visibility = 'hidden'; };
}
el.tip.style.pixelLeft = event.clientX + document.body.scrollLeft - 200
el.tip.style.pixelTop = event.clientY + document.body.scrollTop + 10
el.tip.style.visibility = 'visible';
}
}
the call looks like;
<img id="ContentPlaceHolder1_DocumentList1_dg_imgNotes_0" onmouseover="javascript:showTooltip('<b>Pages:</b> 1<br><b>Date:</b> 8/7/2014<br><b>Rep ID:</b> 789',this,event);" src="/applications/Images/icons/no-a.bmp" align="absmiddle" style="border-width:0px;">
with the event of;
onmouseover="javascript:showTooltip('<b>Pages:</b> 1<br><b>Date:</b> 8/7/2014<br><b>Rep ID:</b> 789',this,event);"
this code has been working without a hitch for upwards of a year and still functions correctly in Firefox and IE, but not is Chrome Version 38.0.2125.111 m. I am no expert, but I feel like the declarations are all fine and the information being passed it alright, but when it hits the function it just steps over the if(document.layers) and the else if(document.all) when debugging, however, when in IE and debugging it steps into the else if statement just find and renders the tooltip for the exact same site.
any help would be appreciated.
document.all and document.layers is obsolete. They are no longer supported by chrome.

Text pagination inside a DIV with image

I want to paginate a text in some div so it will fit the allowed area
Logic is pretty simple:
1. split text into words
2. add word by word into and calculate element height
3. if we exceed the height - create next page
It works quite good
here is JS function i've used:
function paginate() {
var newPage = $('<pre class="text-page" />');
contentBox.empty().append(newPage);
var betterPageText='';
var pageNum = 0;
var isNewPage = false;
var lineHeight = parseInt(contentBox.css('line-height'), 10);
var wantedHeight = contentBox.height() - lineHeight;
for (var i = 0; i < words.length; i++) {
if (isNewPage) {
isNewPage = false;
} else {
betterPageText = betterPageText + ' ' + words[i];
}
newPage.text(betterPageText + ' ...');
if (newPage.height() >= wantedHeight) {
pageNum++;
if (pageNum > 0) {
betterPageText = betterPageText + ' ...';
}
newPage.text(betterPageText);
newPage.clone().insertBefore(newPage)
betterPageText = '...';
isNewPage = true;
} else {
newPage.text(betterPageText);
}
}
contentBox.craftyslide({ height: wantedHeight });
}
But when i add an image it break everything. In this case text overflows 'green' area.
Working fiddle: http://jsfiddle.net/74W4N/7/
Is there a better way to paginate the text and calculate element height?
Except the fact that there are many more variables to calculate,not just only the word width & height, but also new lines,margins paddings and how each browser outputs everything.
Then by adding an image (almost impossible if the image is higher or larger as the max width or height) if it's smaller it also has margins/paddings. and it could start at the end of a line and so break up everything again.basically only on the first page you could add an image simply by calculating it's width+margin and height+margin/lineheight. but that needs alot math to get the wanted result.
Said that i tried some time ago to write a similar script but stopped cause of to many problems and different browser results.
Now reading your question i came across something that i read some time ago:
-webkit-column-count
so i made a different approach of your function that leaves out all this calculations.
don't judge the code as i wrote it just now.(i tested on chrome, other browsers need different prefixes.)
var div=document.getElementsByTagName('div')[0].firstChild,
maxWidth=300,
maxHeigth=200,
div.style.width=maxWidth+'px';
currentHeight=div.offsetHeight;
columns=Math.ceil(currentHeight/maxHeigth);
div.style['-webkit-column-count']=columns;
div.style.width=(maxWidth*columns)+'px';
div.style['-webkit-transition']='all 700ms ease';
div.style['-webkit-column-gap']='0px';
//if you change the column-gap you need to
//add padding before calculating the normal div.
//also the line height should be an integer that
// is divisible of the max height
here is an Example
http://jsfiddle.net/HNF3d/10/
adding an image smaller than the max height & width in the first page would not mess up everything.
and it looks like it's supported by all modern browsers now.(with the correct prefixes)
In my experience, trying to calculate and reposition text in HTML is almost an exercise in futility. There are too many variations among browsers, operating systems, and font issues.
My suggestion would be to take advantage of the overflow CSS property. This, combined with using em sizing for heights, should allow you to define a div block that only shows a defined number of lines (regardless of the size and type of the font). Combine this with a bit of javascript to scroll the containing div element, and you have pagination.
I've hacked together a quick proof of concept in JSFiddle, which you can see here: http://jsfiddle.net/8CMzY/1/
It's missing a previous button and a way of showing the number of pages, but these should be very simple additions.
EDIT: I originally linked to the wrong version for the JSFiddle concept
Solved by using jQuery.clone() method and performing all calculations on hidden copy of original HTML element
function paginate() {
var section = $('.section');
var cloneSection = section.clone().insertAfter(section).css({ position: 'absolute', left: -9999, width: section.width(), zIndex: -999 });
cloneSection.css({ width: section.width() });
var descBox = cloneSection.find('.holder-description').css({ height: 'auto' });
var newPage = $('<pre class="text-page" />');
contentBox.empty();
descBox.empty();
var betterPageText = '';
var pageNum = 0;
var isNewPage = false;
var lineHeight = parseInt(contentBox.css('line-height'), 10);
var wantedHeight = contentBox.height() - lineHeight;
var oldText = '';
for (var i = 0; i < words.length; i++) {
if (isNewPage) {
isNewPage = false;
descBox.empty();
}
betterPageText = betterPageText + ' ' + words[i];
oldText = betterPageText;
descBox.text(betterPageText + ' ...');
if (descBox.height() >= wantedHeight) {
if (i != words.length - 1) {
pageNum++;
if (pageNum > 0) {
betterPageText = betterPageText + ' ...';
}
oldText += ' ... ';
}
newPage.text(oldText);
newPage.clone().appendTo(contentBox);
betterPageText = '... ';
isNewPage = true;
} else {
descBox.text(betterPageText);
if (i == words.length - 1) {
newPage.text(betterPageText).appendTo(contentBox);
}
}
}
if (pageNum > 0) {
contentBox.craftyslide({ height: wantedHeight });
}
cloneSection.remove();
}
live demo: http://jsfiddle.net/74W4N/19/
I actually came to an easier solution based on what #cocco has done, which also works in IE9.
For me it was important to keep the backward compatibility and the animation and so on was irrelevant so I stripped them down. You can see it here: http://jsfiddle.net/HNF3d/63/
heart of it is the fact that I dont limit height and present horizontal pagination as vertical.
var parentDiv = div = document.getElementsByTagName('div')[0];
var div = parentDiv.firstChild,
maxWidth = 300,
maxHeigth = 200,
t = function (e) {
div.style.webkitTransform = 'translate(0,-' + ((e.target.textContent * 1 - 1) * maxHeigth) + 'px)';
div.style["-ms-transform"] = 'translate(0,-' + ((e.target.textContent * 1 - 1) * maxHeigth) + 'px)';
};
div.style.width = maxWidth + 'px';
currentHeight = div.offsetHeight;
columns = Math.ceil(currentHeight / maxHeigth);
links = [];
while (columns--) {
links[columns] = '<span>' + (columns + 1) + '</span>';
}
var l = document.createElement('div');
l.innerHTML = links.join('');
l.onclick = t;
document.body.appendChild(l)

How to detect overlapping HTML elements

Is it possible to find easily elements in HTML page that are hidden by given element (div)?
I prefer jQuery if possible. Do you know such plugin or something?
I searched in jQuery API (http://api.jquery.com/), but didn't find something useful.
One possible solution is jQuery Collision extension: http://sourceforge.net/projects/jquerycollision/.
JQuery extension to return the collisions between two selectors.
Handles padding, margin, borders, and can determine either overlap or
portion outside. Returns JQuery "overlap" objects. Requires:
jquery1.8.3+, examples also require: jqueryui1.9.2+
It sounds like you're looking for something for debugging purposes, but please let me know if I've missed the question!
Firefox has a pretty neat 3D view (info here) that lets you see (more or less) exactly how the objects are being stacked. If you've never looked at it before, it's at least cool enough to check out.
You can use the following script:
http://jsfiddle.net/eyxt2tt1/2/
Basically what it does is:
calculating the dimensions of each DOM element, and comparing with user's mouse coordinate
if the match return a list of DOM elements
$(document).click(function (e) {
var hitElements = getHitElements(e);
var output = $('#output');
output.html('');
for (var i = 0; i < hitElements.length; ++i) {
output.html(output.html() + '<br />' + hitElements[i][0].tagName + ' ' + hitElements[i][0].id);
};
});
var getHitElements = function (e) {
var x = e.pageX;
var y = e.pageY;
var hitElements = [];
$(':visible').each(function () {
console.log($(this).attr("id"), $(this).outerWidth());
var offset = $(this).offset();
console.log('+++++++++++++++++++++');
console.log('pageX: ' + x);
console.log('pageY: ' + y);
console.log($(this).attr("id"), $(this).offset());
console.log('+++++++++++++++++++++');
if (offset.left < x && (offset.left + $(this).outerWidth() > x) && (offset.top < y && (offset.top + $(this).outerHeight() > y))) {
console.log('included: ', $(this).attr("id"));
console.log('from 0p far x: ', $(this).attr("id"), offset.left + $(this).outerWidth());
console.log('from 0p far y: ', $(this).attr("id"), offset.top + $(this).outerHeight());
hitElements.push($(this));
}
});
return hitElements;
}

Categories