Ensure element is always on top - javascript

I'm building a very simple Chrome extension that will put a clickable image on top of any youtube.com page.
The image shows up and has its intended click-functionality, but it is layered below any other elements that appear on the page. This is my code:
const linkItem = document.createElement("a");
linkItem.href="https://www.youtube.com/";
linkItem.innerHTML = "<img src='https://imgur.com/gBgwnSa.png' title='YouTube Home'>";
linkItem.setAttribute("style", "position:absolute;top:50px;left:200px;");
document.getElementsByTagName("body")[0].appendChild(linkItem);
The position is just a placeholder.
How can I set the image to always appear layered above any other elements of the page (preferably without having to create a CSS style sheet)? I know this is a beginner question, but any help would be greatly appreciated! :)

You can use the "z-index" property on CSS. You just have to set it to a value high enough, and it'll always be over everything else that have a smaller/null z-index set.
In this case:
linkItem.setAttribute("style", "position:absolute;top:50px;left:200px;z-index:99");

Related

How can I place a white image at the top and bottom (eg: 40px) of every image in an html file in js?

I am trying to add an image/blank rectangle on top of/overlaid on the top and bottom of every image on an html page. I plan to do this via a user-script, but I could not find any information on how to append an image on another at a specified PX x PX. I am slightly familiar with js. I have done two small hobby projects (an image parser and a poker game) this being the third, and assume I will have to achieve following:
Create a blank image to cover the top and bottom part of the image.
This can be done by creating a simple rectangle I think. I can play with the parameters of the size to make it fit.
get every image on the site
I can probably do this by parsing the DOM (I'm not sure if I need to do this if I am using a user-script) and doing a forEach(img), and within the forEach(img => I can add the rectangle to the top and bottom thereby adding it to every image on the page.
somehow append the blank image from above on top of the top and bottom of each image.
This is where I am lost. I have appended images to the DOM before, but I don't know how to do it through a user-script and I also don't know have to append an image on another image. I have thought of doing the following, but I am unsure how to continue:
I also have linked an example where I would use this user-script. What I am trying to do is remove a watermark. (I am only doing this locally on my computer as to not steal the translators work, which is why I am using JavaScript.) So to recap I am looking for how to solve number 3, and if possible/optionally an explanation of how to do this in grease-monkey or any other user-script manager. Let me know if anything was unclear and thanks to anybody who comments/answers this problem. edit:clarity
here is a link to an example use case
If you just need these two balnk space on each img on the page, just using this css:
img{
height: 945px;
object-fit:cover;
}
Or js:
var x = document.querySelectorAll("img");
var i;
for (i = 0; i < x.length; i++) {
x[i].style.height = "954px";
x[i].style.objectFit = "cover";
}

Get scroll position of HTML element relative to visible portion of container

Right now I have a web page with:
A fixed header at the top of varying size, covering up the page's main content.
A page with a deeply nested scroll container.
Within that container, several other deeply nested elements.
What I want to do is scroll that container so that one of the elements inside lines up with the top of the visible portion of the container. I believe what I am looking for is the top of the nested element relative to the top of the visible portion of the container.
Unfortunately I cannot use .offsetTop because that only references an element's immediate parent, and due to the structure of the page these elements are too deeply nested for that to be of any use. It's always a fixed number. Same with the scroll container; its immediate parent is not the window. Frustratingly, the header is not of a fixed height, so I can't hardcode it into my calculations very easily. I also cannot use jQuery.
I tried using getBoundingClientRect for both the element and the container, but they are always a fixed distance away from each other and it doesn't give me the information I need about how far the element is scrolled relative to the container's visible area, unfortunately.
EDIT: We have a scrolling solution in place already, but we were hoping to improve it through a certain proposed means that I am trying to determine the feasibility of. I would like to ask that everyone please try to only answer the question in bold, rather than proposing alternate solutions. I really do appreciate any help on offer, but I am hoping to get some extremely specific information based on an extremely specific scenario.
I also had this kind of issue earlier, you can try this to auto scroll to the element
var elem = <some select operation that returns the element>;
elem.id = <some temp id> //if no id is there
var a = document.createElement('a');
a.href = "#" + elem.id;
a.click();
If you wish, you can remove the id from your element once its done.

Need to Identify Img Tag by coordinates

I need to change the color of any image that contains a particular x coordinate. However, the code I am using now only gives me the #scrollwrapper container, and not the individual image that is at that location.
var xHome = window.innerWidth/2;
var yHome = window.innerHeight/2;
var pElement = document.elementFromPoint(xHome, yHome);
alert (pElement.className);
This gets wrapper container on the images, but not the particular image that is there. The site is coolaidhouse.com/projectcaptured
You can see the scroller there. I want to dim the images on the side of the "active," item, which is basically the image closest to the middle.
If I could get the image based on its coordinates I could do the rest. However, I can't figure out how to get the image in lieu of the container.
Here is what the end result should look like:
Your code grabs the image when run from the console. Therefore, you need to wait for the image to load before running the code.
IMG elements have an onload event you can use for this purpose.
The answer was in Rick Hitchcock's comment. Don't know how to mark a comment as an answer though. The images were in fact not loaded yet.

Javascript to change the position attribute to static of every style where position attribute is fixed

During some web scraping with Selenium WebDriver with Chrome, I encountered a page that has fixed regions (they do not scroll but stay fixed relative to the window). Oftentimes when I request that the web browser scroll to a particular control using Actions.MoveToElement() , the element winds up being obscured by one of the fixed regions. When Selenium clicks on an obscured element, the fixed region steals the click and my control does not get clicked.
The fixed regions have a class=SomeFixedPositionStyle. To get around this, I'd like to have Selenium inject Javascript code to go through each style on the page and modify it to set position:static if it's position:fixed. How can I do this?
I chose to not modify the class attribute of the fixed elements because the act of scrolling the page resets the class attribute to the original value that has the fixed style.
For example, take a look at http://www.ishares.com/us/products/239572/ishares-jp-morgan-usd-emerging-markets-bond-etf . As you scroll up and down, do you see the bands on the top and the bottom are fixed?
When I try to scroll to element //*[#id="holdingsTabs"]/ul/li[3] (this is the "All" link in the "Holdings" section, it winds up underneath the lower fixed region and cannot be clicked on.
You can inject a style rule into the page
var sheet = document.styleSheets[0];
sheet.insertRule("SomeFixedPositionStyle { position: static!important; }", 1);
What usually helps in situations like this is scrolling into view of an element:
driver.executeScript("arguments[0].scrollIntoView();", element);
You may also get rid of the "stickiness" by dynamically changing the "position" of the wrapper:
var wrapper = driver.findElement(webdriver.By.css('.sticky-wrapper'));
driver.executeScript("arguments[0].style.position = null;", wrapper);

Jquery Remove Image

My overall problem is to lazy load images. I've gotten to the point where I'm loading the images only when they are on screen. I need to remove the images that are not on screen.
I thought
$(image).removeAttr("src")
would do it and it rightly removes src, but it does not clear the image from the screen, nor does it replace it with what is in alt.
How do I make it remove the image? Note, I do not want to remove the img tag (I need it for later), just clear the image from the screen.
Other code that may be relevant(although why I don't know)-
updateCarImages:=>
imagesOnScreen = $(#el).find(".carImageClass:onScreen")
imagesOffScreen = _.without(cachedImagesOnScreen,imagesOnScreen)
for image in imagesOnScreen
imgSrc = $(image).attr("src")
if (!imgSrc)
id = $(image).data("tooltip-id")
console.log(id)
result = resultsStore.get(id+"")
console.log(result)
$(image).attr("src", result.get("carImageUrl"))
console.log(imagesOffScreen)
for image in imagesOffScreen
$(image).removeAttr("src")
If you are trying to clear memory (which as I see it would be the only reason to remove images that are not visible) you are up for a ride.
There is no bullet proof way to force a browser to do that. The only way the browser will call the garbage collector is to reach a certain memory limit, and then hint the collector what it should take first.
Moving nodes to a bin and empty it is considered a good way:
var $trash = $('<div>').hide().appendTo('body');
var waste = function(node) {
$trash.append(node).html('');
}
You might get lucky with replacing the source with an empty GIF:
$(image).attr('src','data:image/gif;base64,R0lGODlhAQABAPABAP///wAAACH5BAEKAAAA‌​LAAAAAABAAEAAAICRAEAOw%3D%3D');
This will also keep the node in place and image width/height.
But I highly doubt that any of this will result in any performance gain in your case, the best thing is to not stress the browser with too much data at all.
iOS for iPad (especially version 4.x) is known for having a low memory limit and can easilly crash if you leave too many IMG nodes around.
To hide the image:
$(image).hide();
This will set style="display:none;" on the image and make it not appear
To delete the image:
$(image).remove();
This will Physically remove it from the DOM so it no longer exists
Hybrid approach (leaves the image in the DOM and allows you to change it later)
//Remove the SRC and hide the image
$(image).removeAttr("src").hide();
//Then when you want to change to a new image
$(image).attr("src", "iamge.gif").show();
If your issue is performance, then you can use a pre-existing lazy load jQuery plugin. There is no point re-inventing the wheel.
http://www.appelsiini.net/2012/lazyload-170
Alternatively if you don't wish to use this plugin you could store the src value in a data-* attribute and only attach it to src when you wish to display it.
When hiding:
$(image).data("src", $(image).attr("src"));
$(image).removeAttr("src");
$(image).hide();
When displaying:
$(image).attr("src", $(image).data("src"));
$(image).show();
You can simply hide the image. If you don't wat to go there , you can maybe create a 1px image and than :
$(image).attr('src', '1px.png');
If you want to hide the image, but keep it in place in terms of taking up its space and not affecting container's scrollbars, use visibility: hidden style:
$(image).css('visibility', 'hidden');
You can simply remove image from this code. I have tried it.
$('.img2').dblclick(function()
{
$(".img2").removeAttr('src');
});
This following code shows how I was able to remove the image source
var image_holder = $("#preview-image-holder");
image_holder.empty();

Categories

Resources