How to detect overlapping HTML elements - javascript

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;
}

Related

Jquery change color of SVG element using jscolor.js is failing

I have a web page in which SVG is embedded. I am pulling references of elements of SVG and creating color swatches for every element using jscolor.js library.
I want to adjust color of these elements using swatches I am dynamically creating on click jquery event listener.
The problem is, after couple of changes SVG element is becoming black due to some error which is assigning 'undefined' fill color to this SVG element.
I am not getting why it not working all the time.
The main function to do this job is as follows
$("#svg_obj").on("click", ".badge", function(event) {
event.stopPropagation();
var rect = event.target.getBoundingClientRect();
$(".badge").attr('selection', null);
this.setAttribute('selection', true);
var svg_left = ((Math.round(this.getAttribute('width')) - Math.round(this.getBoundingClientRect().width)) / 2);
$(".selector").css("left", Math.round(this.getBoundingClientRect().x - svg_left) + 'px')
$(".selector").css("top", Math.round(this.getBoundingClientRect().y) + 'px')
$(".selector").css("width", Math.round(this.getAttribute('width')) + 'px');
$(".selector").css("height", Math.round(this.getAttribute('height')) + 'px');
$(".selector").css("visibility", "visible");
for (let i = 0; i < this.childNodes.length; i++) {
var svg_g = this.childNodes[i];
// console.log(this.childNodes[i].nodeName);
if (svg_g.nodeName == 'g') {
var polygons = Array.from(svg_g.querySelectorAll("polygon"));
var polygons = polygons.concat(Array.from(svg_g.querySelectorAll("path")));
// console.log(polygons);
Object.values(polygons).forEach(val => {
// console.log(val.attributes.fill.value.substring(1));
console.log(val);
$("#status_bar").append("<p class='swatches " + val.attributes.fill.value.substring(1) + "' >Color:<input data-jscolor='{position:"right"}' value='" + val.attributes.fill.value + "'></p>").on('change', '.' + val.attributes.fill.value.substring(1), function() {
val.attributes.fill.value = $('#status_bar .' + val.attributes.fill.value.substring(1)).find('input').val();
console.log($('.' + val.attributes.fill.value.substring(1)).find('input').val());
});
});
} else {
// console.log("Not a group " +svg_g);
}
}
jscolor.install();
});
jsfiddle for working code
Could you please help to fix this issue?
Thanks

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)

What is the most efficient way to do this (jquery snippet)?

$("#content").scroll(function(e){
var distance_from_top = $("#content").scrollTop();
var theinverse = -1 * distance_from_top;
var theinverse2 = theinverse + "px";
$("#topheader").css( "marginTop", theinverse2);
});
What's the most efficient way to do the above? Basically make #topheader top margin equal to the negative distance scrolled from the top.
caching caching caching.
content = $("#content");
topheader = document.getElementById("topheader");
content.scroll(function() {
topheader.style.marginTop = -content.scrollTop() + "px";
});
Efficient or short because you could simply do this for shortness.
$("#content").scroll(function(e){
$("#topheader").css( "marginTop", -$("#content").scrollTop() + "px");
});
When probably need more context (source of the web page) if you want efficiency.

JavaScript script doesn't work in Firefox

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;

How to get a list of all elements that resides at the clicked point?

On user click I would like to get a list of all elements that resides at the clicked point.
For example, if user clicks on Hello here:
<div><span>Hello<span></div>
I would like to get the following list:
<span> element
<div> element
<body> element
<html> element
What would be the easiest method to get these elements ?
EDIT: Based on clarification, I think this is what you mean:
EDIT: As pointed out by #Misha, outerWidth() and outerHeight() should be used in lieu of width() and height() in order to get an accurate range.
Also, if there's nothing to prevent event bubbling on the page, then the click should be placed on the document as it will be much more efficient. Even if some other click handler prevents bubbling, you should still have the click on the document, and just handle it separately from those handler that prevent bubbling.
Example: http://jsfiddle.net/57bVR/3/
$(document).click(function(e) {
var clickX = e.pageX
,clickY = e.pageY
,list
,$list
,offset
,range
,$body = $('body').parents().andSelf();
$list = $('body *').filter(function() {
offset = $(this).offset();
range = {
x: [ offset.left,
offset.left + $(this).outerWidth() ],
y: [ offset.top,
offset.top + $(this).outerHeight() ]
};
return (clickX >= range.x[0] && clickX <= range.x[1]) && (clickY >= range.y[0] && clickY <= range.y[1])
});
$list = $list.add($body);
list = $list.map(function() {
return this.nodeName + ' ' + this.className
}).get();
alert(list);
return false;
});​
Original answer:
This will give you an Array of the tag names including the span. Couldn't quite tell if this is what you wanted.
It uses .parents() along with .andSelf() to get the elements, then uses .map() with .get() to create the Array.
Example: http://jsfiddle.net/9cFTG/
var list;
$('span').click(function() {
list = $(this).parents().andSelf().map(function() {
return this.nodeName;
}).get();
alert(list);
});​
If you just wanted the elements, not the tag names, get rid of .map() and .get().
Or if you wanted to join the Array into a String using some sort of separator, just add .join(" ") after .get(), placing your separator inside the quotes.
In the near future this should be possible:
$(document).click(function(e) {
var family = this.elementsFromPoint(e.pageX, e.pageY);
$(family).each( function () {
console.log(child);
});
});
Update 2019
Currently in editors draft:
Elements from point
use parent method to get parent of the current tag recursively or in cycle:
var parentTag = $(this).parent().get(0).tagName;
The jQuery parents() function can do this for you.
To attach a click event to all span tags, for example:
$("span").click(function() {
var parents = "";
$(this).parents().map(function () {
parents = parents + " " + this.tagName;
})
alert(parents);
});
Try something like this
$('span').click(function() {
var parents = $(this).parents();
for(var i = 0; i < parents.length; i++){
console.log($(parents[i]).get(0).tagName)
}
});
check the live demo
http://jsfiddle.net/sdA44/1/
Just javascript implementation:
window.addEventListener('click', function(e){
console.log(document.elementFromPoint(e.pageX, e.pageY))
}, false)
Worked for me in firefox and chrome as of 3-29-2017
Found this:
https://gist.github.com/osartun/4154204
Had to change elements.get(i) to elements[i] to fix it...
I have updated the demo http://jsfiddle.net/57bVR/3/, adding to the code the logic to manage also (if present):
The scrolling of the page
The zoom level html tag (in the project I work it gives to me several troubles)
$(document).click(function (e) {
var htmlZoom = window.getComputedStyle(document.getElementsByTagName('html')[0]).getPropertyValue('zoom');
var clickX = e.pageX,
clickY = e.pageY,
list,
$list,
offset,
range,
$body = $('body').parents().andSelf();
$list = $('body *').filter(function () {
offset = $(this).offset();
marginLeft = offset.left * htmlZoom - $(document).scrollLeft();
marginTop = offset.top * htmlZoom - $(document).scrollTop();
outerWidth = $(this).outerWidth() * htmlZoom;
outerHeight = $(this).outerHeight() * htmlZoom;
range = {
x : [marginLeft,
marginLeft + outerWidth],
y : [marginTop,
marginTop + outerHeight]
};
return (clickX >= range.x[0] && clickX <= range.x[1]) && (clickY >= range.y[0] && clickY <= range.y[1])
});
$list = $list.add($body);
list = $list.map(function () {
return this.nodeName + ' ' + this.className
}).get();
alert(list);
return false;
});

Categories