I'm developing a Firefox extension which amends the contents of a loaded webpage. First I select all the elements of which the "src" or "href" attributes match my regex (this part of the code works).
Then, I would like to place a little image at the top right corner of the found element's parent using the following code:
/* create and add attributes to image */
var img = window.content.document.createElement("img");
var b = window.content.document.createAttribute("src");
b.nodeValue = "chrome://plugin/content/agent.png";
img.setAttributeNode(b);
img.addEventListener("click", function(){ alert("ds"); });
img.style.display = "block";
img.style.border = "3px solid red";
img.style.position = "relative";
img.style.top = "-10px";
img.style.right = "-10px";
img.style.left = "20px";
// ... the code to return the element...
//now insert the image
$jq(img).appendTo(element.parentNode);
The current result is that either the image is shown just at the bottom of the element's parent or not shown at all.
If you look at this: http://jsfiddle.net/yzwh5/64/ - I would like my button to work in a similar manner to that red cross.
You must "play" with the element's CSS positioning, in fact it doesn't matter where do you insert the images, but where you do position them.
Maybe you would like to take a look at "next-to", a jQuery plugin that automates the calculations to position an element next to another element
For example:
<script type="text/javascript">
$('.PlaceThisDiv').nextTo($('.ThisOtherDiv'), {position:'right', shareBorder:'top'});
</script>
As you can see in this Fiddle i have prepared (contains the plugin itself)
http://jsfiddle.net/PvcNr/
you will get you something like this:
More info: https://code.google.com/p/next-to/
Hope it helps
Try CSS code like this:
.my-ext-overlay:after {
content:url(smiley.gif);
position: absolute;
margin-left: -16px; margin-top: -16px;
}
and then adding the ".my-ext-overlay" class name to each element you find.
See example
Firstly, CSS floats are called cssFloat (or htmlFloat in some browsers) because float is a reserved word. Second, there is no such float value as block.
Third, you missed an x in -10px for the right property.
Fourth, setting both relative left and right positions can lead to unexpected behaviour.
Fifth, you shouldn't use createAttribute, since attribute nodes aren't reliable in all browsers. Instead, use setAttribute on the element.
Sixth, if this did work it would mess up page layout around the element you're searching for, so you would be better off with position: absolute so it doesn't affect the flow. If you do this, however, you should use margin-left instead of left (same for other directions), to shift the element around.
I think that should at least get the thing close to working...
Related
I'm around trying to remove a DOM element (I'll put it elsewhere) and I need the position of the sibling elements do not change.
I tried some variations of this.
var elem = $("#theElement");
var ghost = $('<div></div>');
ghost.css({
width: elem.outerWidth(true),
height: elem.outerHeight(true),
margin: 0
});
elem.replaceWith(ghost);
But the document collapses slightly.
I know I can just change the visibility of the element, but not what I need. I'll put it somewhere else in the DOM and can not be duplicated.
The Question
How to replace any kind of element with a div that occupies the same space?
EDIT
Keep in mind that i can not change the source element attributes.
I do not know in advance which item and which properties it has, just take it out of where it is and move it elsewhere.
The jQuery documentation says:
.outerHeight(true): if the includeMargin argument is set to true, the margin (top and bottom) is also included.
.outerWidth(true): If includeMargin is omitted or false, the padding and border are included in the calculation; if true, the margin is also included.
plunker
That is because of the margin given by the browser, called user agent stylesheet in dev tools.
I have modified your plunk to have css like this
h1 {
color: red;
margin:0px !important;
}
Issue seemed to be resolved.
EDIT:
I have edited your code to be something like this:
$(function(){
var elem = $("h1");
var ghost = $('<div></div>');
ghost.css({
width: elem.outerWidth(),
height: elem.outerHeight(),
margin: 21
});
Since you can not modify the source, identify what styling the browser is putting onto it and give your ghost element the same styling.
To detect what css the browser is putting onto your element, refer
http://www.iecss.com
http://mxr.mozilla.org/mozilla-central/source/layout/style/html.css
http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css
Is it possible to get the width (using javascript or jQuery) of a float-affected element? When text is being pushed over due to a floating image is it possible to get its position and true width? I have attached an image to explain better.
Code example,
<div>
<img style="...float: left"/>
<h1>A title!</h1>
<p>Text!</p>
<h1>New header added.</h1>
</div>
Picture
I need to find the width starting from the arrow, (the gray box is the image)(the dotted line is the width according to Firefox inspect mode).
I would like to avoid changing all the elements display types if possible.
Thank you!
I'm a little late to the party, but I had a similar problem and came up with a solution which (so far) seems to work in all instances of this issue. I like this solution because as far as I can tell, it works independent of the floating element - all you need is the element whose true width/position you want to get, nothing more. I've done it in pure Javascript for speed purposes, but it can easily be streamlined with jQuery and a separate CSS Stylesheet if you so choose.
//Get the rendered bounding box for the content of any HTMLElement "el"
var getLimits = function(el) {
//Set a universal style for both tester spans; use "!important" to make sure other styles don't mess things up!
var testerStyle = 'width: 0px!important; overflow: hidden!important; color: transparent!important;';
//Create a 'tester' span and place it BEFORE the content
var testerStart = document.createElement('SPAN');
testerStart.innerHTML = '|';
var testerFloat = ' float: left!important;';
testerStart.setAttribute('style', testerStyle + testerFloat);
//Insert testerStart before the first child of our element
if (el.firstChild) {
el.insertBefore(testerStart, el.firstChild);
} else {
el.appendChild(testerStart);
}
//Create a 'tester' span and place it AFTER the content
var testerEnd = document.createElement('SPAN');
testerEnd.innerHTML = '|';
testerFloat = ' float: right!important;';
testerEnd.setAttribute('style', testerStyle + testerFloat);
el.appendChild(testerEnd);
//Measure the testers
var limits = {
top: testerStart.offsetTop,
bottom: testerEnd.offsetTop + testerEnd.offsetHeight,
left: testerStart.offsetLeft,
right: testerEnd.offsetLeft
}
//Remove the testers and return
el.removeChild(testerStart);
el.removeChild(testerEnd);
return limits;
};
So, in your case, the code would just be:
var paragraphBoundingBox = getLimits($('div>p').get(0));
A couple things to note:
1) The float direction would be reversed if you are using an RTL language
2) All of the four edge positions in the output object are relative to the el.offsetParent - use this handy function can find their positions relative to the document.
First of all, the "full width" is exactly the true width.
You can watch this picture, it can help you understand why the true width and true position of the affected element is the way firefox tells you.
http://i.stack.imgur.com/mB5Ds.png
To get the width of inline text where it's pushed right by the float image, there's no good way except using the full width minus the float image's width.
var w = $('p').width()
- $('img').width()
- $('img').css('margin-left').replace("px", "")
- $('img').css('margin-right').replace("px", "")
- $('img').css('padding-left').replace("px", "")
- $('img').css('padding-right').replace("px", "")
- $('img').css('border-left-width').replace("px", "")
- $('img').css('border-right-width').replace("px", "");
I have a div element which I'm using as a pop-over search field which I want to have appear under the element which is being filtered. However, it seems that I cannot use the style.bottom and style.left of the element I want the field to be relative to as this element is static.
Example is here: http://www.is-epic.co.uk/example/example.html
Clicking the Header 2 link will have the input box appear, in the top-left corner of the table. I would like it to appear roughly where Data 1.2 is. How do I achieve this?
(Code in example.html is on one page, in live dev CSS and JS are in separate files)
Set the element you wish to position the other element with respect to to position: relative.
This will make it the containing block for any descendants that are position: absolute (unless an element between the two is also position: not static).
this works in FF and Google-Chrome
var head = document.getElementById("header_2");
var filter = document.getElementById("search_filter");
filter.style.display = "";
filter.style.left = head.offsetLeft + 'px';
filter.style.top = head.offsetTop + head.offsetHeight + 'px';
it should work with IE as well..
i used variables filter and head to cut down on typing :)
The problem is that for header_2 both style.left and style.bottom are 0, so that
document.getElementById("search_filter").style.left =
document.getElementById("header_2").style.left;
document.getElementById("search_filter").style.top =
document.getElementById("header_2").style.bottom;
is equivalent to
document.getElementById("search_filter").style.left = 0;
document.getElementById("search_filter").style.top = 0;
which is exactly what happens. You have to find out header_2's actual position, e.g. using jQuery.
I'm currently extending the lavalamp plugin to work on dropdown menus but I've encountered a small problem. I need to know the offsetWidth of an element that is hidden. Now clearly this question makes no sense, rather what I'm looking for is the offsetWidth of the element were it not hidden.
Is the solution to show it, grab the width, then hide again? There must be a better way...
The width of an element that has CSS visibility: hidden is measurable. It's only when it's display: none that it's not rendered at all. So if it's certain the elements are going to be absolutely-positioned (so they don't cause a layout change when displayed), simply use css('visibility', 'hidden') to hide your element instead of hide() and you should be OK measuring the width.
Otherwise, yes, show-measure-hide does work.
The only thing I can think of is to show it (or a clone of it) to allow retrieval of the offsetWidth.
For this measurement step, just make its position absolute and its x or y value a big negative, so it will render but not be visible to the user.
You can use the following function to get the outer width of an element that is inside a hidden container.
$.fn.getHiddenOffsetWidth = function () {
// save a reference to a cloned element that can be measured
var $hiddenElement = $(this).clone().appendTo('body');
// calculate the width of the clone
var width = $hiddenElement.outerWidth();
// remove the clone from the DOM
$hiddenElement.remove();
return width;
};
You can change .outerWidth() to .offsetWidth() for your situation.
The function first clones the element, copying it to a place where it will be visible. It then retrieves the offset width and finally removes the clone. The following snippet illustrates a situation where this function would be perfect:
<style>
.container-inner {
display: none;
}
.measure-me {
width: 120px;
}
</style>
<div class="container-outer">
<div class="container-inner">
<div class="measure-me"></div>
</div>
</div>
Please be aware that if there is CSS applied to the element that changes the width of the element that won't be applied if it's a direct descendant of body, then this method won't work. So something like this will mean that the function doesn't work:
.container-outer .measure-me {
width: 100px;
}
You'll either need to:
change the specificity of the CSS selector ie. .measure-me { width: 100px; }
change the appendTo() to add the clone to a place where your CSS will also be applied to the clone. Ensure that where ever you do put it, that the element will be visible: .appendTo('.container-outer')
Again, this function assumes that the element is only hidden because it's inside a hidden container. If the element itself is display:none, you can simply add some code to make the clone visible before you retrieve it's offset width. Something like this:
$.fn.getHiddenOffsetWidth = function () {
var hiddenElement $(this)
width = 0;
// make the element measurable
hiddenElement.show();
// calculate the width of the element
width = hiddenElement.outerWidth();
// hide the element again
hiddenElement.hide();
return width;
}
This would work in a situation like this:
<style>
.measure-me {
display: none;
width: 120px;
}
</style>
<div class="container">
<div class="measure-me"></div>
</div>
Two options:
position the element outside the viewport (ex: left:-10000px)
use visibility: hidden or opacity: 0 instead of hide().
Either way will work as hiding the element but still being able to get the computed width. Be careful with Safari on thi, it's awfully fast and sometimes too fast...
Actual jQuery plugin!
Usage:
console.log('width without actual: ' + $('#hidden').width());
console.log('width with actual: ' + $('#hidden').actual('width'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.actual/1.0.19/jquery.actual.min.js"></script>
<div style="width: 100px; display: none;">
<div id="hidden"></div>
</div>
If you know the element to be the full width of a parent element another approach is to create a recursive method:
es5:
var getWidth;
getWidth = function($el){
return $el.offsetWidth || getWidth($el.parentElement);
}
var width = getWidth(document.getElementById('the-element'));
es6:
let getWidth
getWidth = ($el) => $el.offsetWidth || getWidth($el.parentElement)
const width = getWidth(document.getElementById('the-element'))
What I did was ;
by the time hiding that element, stored its width in its dataset.
It only will work for you if you can hide programmatically.
ie.
When Hiding ;
var elem = $("selectorOfElement");
elem.dataset.orgWidth = elem.clientWidth;
Later when getting ;
var elem = $("selectorOfElement");
var originalWidthWas = elem.dataset.orgWidth;
thats because its hidden via display: none; What ive done in the past is to make a "reciever" div which i use absolute positioning on to get it off the page. Then i load the new element into that, grab the dimensions and then remove it when im done - then remove the reciever when im done.
Another thing you can do is to not use hide(); but to instead set visibility: hidden; display: ; However this means the blank area will be rendered wherever the node is attached.
var $hiddenElement = $('#id_of_your_item').clone().css({ left: -10000, top: -10000, position: 'absolute', display: 'inline', visibility: 'visible' }).appendTo('body');
var width = parseInt($hiddenElement.outerWidth());
$hiddenElement.remove();
I try to find working function for hidden element but I realize that CSS is much complex than everyone think. There are a lot of new layout techniques in CSS3 that might not work for all previous answers like flexible box, grid, column or even element inside complex parent element.
flexibox example
I think the only sustainable & simple solution is real-time rendering. At that time, browser should give you that correct element size.
Sadly, JavaScript does not provide any direct event to notify when element is showed or hidden. However, I create some function based on DOM Attribute Modified API that will execute callback function when visibility of element is changed.
$('[selector]').onVisibleChanged(function(e, isVisible)
{
var realWidth = $('[selector]').width();
var realHeight = $('[selector]').height();
// render or adjust something
});
For more information, Please visit at my project GitHub.
https://github.com/Soul-Master/visible.event.js
demo: http://jsbin.com/ETiGIre/7
Sorry I am late to this conversation. I am surprised no one has mentioned getComputedStyle. (Note this only works if the CSS sets a width value)
Grab the element:
let yourEle = document.getElementById('this-ele-id');
and use the function:
getComputedStyle(yourEle).width
This returns a string so you will have to remove the numbers from the string.
This works even when the element's display style is set to none.
Other articles to read about this includes here at zellwk.com
i am new at javascript. very new actually, this ought to be my first script.
can anyone explain to me how to make a transparent overlay over any specified fixed width region, say 700x300px.
You can define the overlay such as
<div id="myoverlay" class="myoverlay">...contents...</div>
and define the dimensions and position and z-index etc... in CSS
.myoverlay {
position: absolute;
display: none;
...
}
I don't quite see the need for JavaScript just yet, but I guess you will want to use JS to toggle the overlay's display attribute on/off.
<script type="text/javascript">
function showOverlay(){
document.getElementById("myoverlay").style.display = "block";
}
</script>
Is this roughly what you're after? Sorry for unintentional syntax mistakes, for this is untested code purely off the top of my head. Just to give you an idea.
You can create a div with transparency and absolutely position it over the specified region.
var shimDiv = document.createElement('div');
shimDiv.id = 'shim';
shimDiv.style.position = 'absolute';
shimDiv.style.top = 0;
shimDiv.style.left = 0;
shimDiv.style.width = "700px";
shimDiv.style.height = "300px";
shimDiv.style.backgroundColor = '#000';
shimDiv.style.zIndex = 3;
For non IE browsers set opacity:
shimDiv.style.opacity = '0.75';
As IE doesn't natively support transparency you should use the filter like this:
shimDiv.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=75)';
And add this new div to the end of the document body:
document.body.appendChild(shimDiv);
To support older IE versions you will have to put IFrame element under your transparent DIV.
To create IFrame dynamically from JavaScript try the following code:
var iframe = document.createElement('iframe');
iframe.setAttribute("src", "javascript:false");
Don't forget to set IFrame src attribute with useless 'javascript:false' statement to prevent IFrame from trying to load the page (which you won't notice it doing, but it will be the cause for tripping the "Unsecured Items" message if you use it on a HTTPS page).
Position this IFrame under the div by giving it a lower z-index property value.
iframe.style.zIndex = 2;
All the styling can be done with CSS. I just wanted to show how it done with JavaScript.