This question already has answers here:
jQuery jump or scroll to certain position, div or target on the page from button onclick [duplicate]
(2 answers)
Scroll to an element with jQuery
(32 answers)
Closed 6 years ago.
It is possible to move to a certain position on a page using #elementId. How can I do the same thing using Javascript / Jquery. When a JS function is called, I want to scroll to the specific position on that page.
After much googling I found that you just need to do this:
location.hash = "elementId"
Another solution is scrollIntoView()
document.getElementById("elementID").scrollIntoView();
Here's an example function that I tested on today's New York Times front page using the browser console:
function scrollToElement(pageElement) {
var positionX = 0,
positionY = 0;
while(pageElement != null){
positionX += pageElement.offsetLeft;
positionY += pageElement.offsetTop;
pageElement = pageElement.offsetParent;
window.scrollTo(positionX, positionY);
}
}
var pageElement = document.getElementById("insideNYTimesHeader");
scrollToElement(pageElement);
you can use scrollTop to scroll up.
you can use this plugin too
Related
This question already has answers here:
Cross domain iframe issue
(5 answers)
Adding click event handler to iframe
(2 answers)
Closed 4 years ago.
Through a script tag I've inserted on an external site, I am trying to load in some javascript which iframes a widget I am hosting on a webpage,
I only want the small launcher icon iFramed initially and then when its opened, iFrame the entire chat window when it's expanded. As Iframing the whole thing takes up a lot of the external site and means everything behind is isnt reachable!
My thought was to have a small iframe initialy and then when it's clicked, increase it's size to the entire window and then while doing so, add an element in the area where the launcher is to then close it when pressed and reduce the iframe size again! hacky I know but i dont know how else I can do this?
What you can see is me creating an iframe, and trying to give it an id
of 'ifrm' with the line:
the code so far: ifrm.setAttribute("id", "ifrm");
. AND then try to change the iframes CSS or append a new one? BUT this doesnt call the function when clicked so i may
have the setting of the ID / calling it wrong?
Then how would I append an element? sorry ive probably gone the wrong way about this.
prepareFrame();
function prepareFrame() {
console.log("yes this consoles inside of prepareFrame")
var ifrm = document.createElement("iframe");
ifrm.setAttribute("src", "https://5efae1b1.ngrok.io");
ifrm.style.width = "100px";
ifrm.style.height = "100px";
ifrm.style.position="fixed";
ifrm.style.right="0";
ifrm.style.bottom="0";
ifrm.style.border="0";
ifrm.setAttribute("id", "ifrm");
document.body.appendChild(ifrm);
document.getElementById("ifrm").addEventListener("click", function(){click1(1);}, false);
}
function click1() {
alert("calling");
document.getElementById("ifrm").style.backgroundColor = '#ff0000';
colorcheck = document.getElementById("ifrm").style.backgroundColor;
console.log('colour check' + colorcheck);
};
Thanks so much if you can help!
Instead of doing this:
document.getElementsByTagName("iframe")[0].setAttribute("id", "ifrm");
Try this at the beginning of your iframe creation:
var ifrm = document.createElement("iframe");
ifrm.setAttribute('id', 'ifrm'); // assign an id
add ifrm.contentDocument.addEventListener("click", function(e){click1(e)}, false) to inside the prepareFrame function, this will then call the click1 function.
This question already has answers here:
iFrame src change event detection?
(7 answers)
Closed 8 years ago.
I have an iframe. I want to create a loop in Javascript that monitors the iframe's URL. So what I want is something like this:
while(1){
if(iframe.src == "foo"){
iframe.src = "bar"
}
}
What's the correct way to do this (ideally without jQuery etc)?
If you have an infinite loop you have to stop it manually using break:
while (1) {
if(...) {
...
break; //exit loop
}
}
Is this what you wanted to ask? Feel free to ask any further question.
Edit:
The solution I would choose is creating an own event to listen for and a function to trigger the event if needed:
var iframeSrcChangeEvt = new Event("iframeSrcChanged"); //create event
document.querySelector("iframe").addEventListener("iframeSrcChanged",function() { //add event listener to the iframe
this.src = "bar"; //change src as you need it
this.removeEventListener("iframeSrcChanged"); //remove listener if fired
clearInterval(monitorIframe); //stop monitoring the iframe
});
var monitorIframe = setInterval(function() { //set an interval to monitor the iframe
var iframe = document.querySelector("iframe");
if(iframe.src == "foo") {
iframe.dispatchEvent(iframeSrcCHangeEvt); //fire event
}
},500);
I think this solution is better because you are able to add more than one iframe to monitor if you adapt that code.
For a mockup-webpage used for research on interaction on websites, I created a mockup message-stream using JavaScript. This message stream is loaded in an IFrame and should show images at pre-set intervals and scroll to the bottom of the page after placing a new image at the bottom of the page. Getting the images to appear is working quite well with the provided script. However, both Chrome and IE seem to have trouble scrolling the page to the bottom. I would like to scroll to the bottom of the page as soon as the image is attached, but have for now added a 5 ms delay because that seemed to work sometimes. My questions are:
Is it okay to use document.body.scrollHeight for this purpose?
Can I make the scroll occur directly, or do I need a small interval before scrolling?
How to make the code scroll to the bottom of the IFrame directly after adding an image?
The following functions are used and trypost() is started onLoad:
function scrollToBottom(){
window.scrollBy(0,document.body.scrollHeight);
}
function trypost(){
point = point + 1;
if(point < interval.length){
//create and append a new image
var newImg = document.createElement("IMG");
newImg.src = "images/"+images[point]+".png";
document.getElementById('holder').appendChild(newImg);
//create and append a return
var br = document.createElement("br");
document.getElementById('holder').appendChild(br);
//time scroll to bottom (after an arbitrary 5 seconds)
var stb = window.setTimeout(scrollToBottom, 5);
//time next post
var nextupdate = interval[point]*400;
var tp = window.setTimeout(trypost, nextupdate);
}
}
My script section contains at least the following variables:
var point = -1;
var interval = [10, 10, 15];
var images = ["r1", "a1", "r2"];
This questions is a continuation of the project described in How to proper use setTimeout with IE?
To answer one of your questions, document.body.scrollHeight is appropriate for this purpose, but not if you're actually calling for document. That'll give you the scroll height of the document the iFrame is in, not the iFrame's document. The iFrame's document can be called upon by [insert variable for iFrame here].contentDocument.
Here's how I did it (and by that, I mean I tested it out with my own stuff to make sure it worked):
let i = document.querySelector('iframe')
i.contentWindow.scrollTo(0, i.contentDocument.body.scrollHeight);
That being said, the other answer by Thomas Urban will also work most of the time. The difference is only if your page has a really long scroll height. Most pages won't be longer than 999999 (for all I know that's impossible and that's why they chose that number), but if you have a page longer than that, the method I showed here would scroll to the bottom and the 999999 would scroll to somewhere not yet at the bottom.
Also note, if you have more than one iFrame, you're gonna want to query it in a different way than I did, like by ID.
Scrolling to bottom is always like scrolling to some ridiculously large top offset, e.g. 999999.
iframe.contentWindow.scrollTo( 0, 999999 );
In addition see this post: Scrolling an iframe with javascript?
If scrolling occurs too early it's probably due to images not being loaded yet. Thus, you will have to scroll as soon as added image has been loaded rather than on having placed it. Add
newImg.onload = function() { triggerScrolling(); };
after creating newImg, but before assigning property src.
If several events are required to trigger scrolling you might need to use some "event collector".
function getEventCollector( start, trigger ) {
return function() {
if ( --start == 0 ) { trigger(); )
};
}
You can then use it like this:
var collector = getEventCollector( 2, function() { triggerScrolling(); } );
newImg.onload = collector;
window.setTimeout( collector, 100 );
This way triggerScrolling() is invoked after 100ms at least and after image has been loaded for collector has to be invoked twice for triggerScrolling() being invoked eventually.
I've written a rather basic js function that programatically and automatically aligns the iPhone keyboard perfectly underneath each and every input field that gets focused (feel free to use it if you like it!). The alignment's primarily handled by window.scroll - a standard method that works in any browser view, except in UIWebView hence phonegap/cordova (2.1). So I need a workaround.
My working code:
function setKeyboardPos(tarId) {
//programmatically: set scroll pos so keyboard aligns perfectly underneath textfield
var elVerticalDistance = $("#"+tarId).offset()["top"]; //i.e. 287
var keyboardHeight = 158;
var heightOfView = document.height; // i.e. 444
var inputHeight = $("#"+tarId).outerHeight();
var viewPortSpace = heightOfView-keyboardHeight; //i.e. 180
var verticalNewSroll = (elVerticalDistance+inputHeight)-viewPortSpace;
if(verticalNewSroll<0) { verticalNewSroll = 0; }
////
//OK, all done lets go ahead with some actions
$("#footer").hide(); //hide footer so that the keyboard doesn't push it on top of textfield
$("#containingDiv").css("bottom","0px"); //remove bottom space for footer
window.scrollTo(0,verticalNewSroll); //scroll! where the problem starts
}
Working in everything but UIWebView, that is. As I mentioned above, everything works except the window.scrollTo (N.B. some minor changes have been made for the sake of clarity). So does anyone know of an alternative solution or even a good workaround?
Similar questions
window.scrollTo doesn't work in phonegap for IOS
PhoneGap / Cordova scrollTo Ignored
How to add vertical scroll in Phonegap
Above are furthermore three similar questions that somewhat points one in the right direction. One of the answerers mentions the use of css to accomplish this. Can anyone come up with a more concrete example? Another guy suggests anchors but that's not a very pretty solution and doesn't go very well with the rest of my code.
After doing some research, I realized window.scrollTo() does actually work in iOS6 with phonegap 2.1, there was something else that failed; for some reason, document.height didn't yield a property of equal proportion within UIwebView so I had to write a small workaround. I'll post the solution and the entire code below for future reference.
function setKeyboardPos(tarId) {
//programmatically: set scroll pos so keyboard aligns perfectly underneath textfield
var elVerticalDistance = $("#"+tarId).offset()["top"];
var keyboardHeight = 157;
if(isNativeApp()) { keyboardHeight = 261; } //I choose to change the keyboard height for the sake of simplicity. Obviously, this value does not correnspond to the actual height of the keyboard but it does the trick
var keyboardTextfieldPadding = 2;
var heightOfView = document.height;
var inputHeight = $("#"+tarId).outerHeight();
var viewPortSpace = heightOfView-keyboardHeight-keyboardTextfieldPadding; //180
var verticalNewSroll = (elVerticalDistance+inputHeight)-viewPortSpace;
if(verticalNewSroll<0) { verticalNewSroll = 0; }
////
//OK, all done lets go ahead with some actions
$("#footer").hide(); //hide footer so that the keyboard doesn't push it on top of textfield
$("#containingDiv").css("bottom","0px"); //remove bottom space for footer
window.scrollTo(0,verticalNewSroll); // perform scroll!
}
function isNativeApp() {
var app = (document.URL.indexOf('http://') === -1) && (document.URL.indexOf('https://') === -1);
if (app) {
return true; // PhoneGap native application
} else {
return false; // Web app / safari
}
}
you can try and use the animate and scrollTop property to scroll It looks something like this:
$("html, body").animate({ scrollTop: "The value to scroll to" });
Hope this helps.
You just need to use this:
$(window).scrollTop(0);
After looking for several hours and not finding an answer either way I decided to come to you, oh great community of people who I always look to for help. I have an iframe that when scrolled by my user, they leave, then come back, we'd like to use scrollto to bring back to the right position. So how can I save/export/add to variable the x and y of this iframe or is that impossible?
You can save the x,y variables to cookie using this jquery plugin: https://github.com/carhartl/jquery-cookie
Example:
$(window).unload(function() {
//save scroll on unload
$.cookie('scroll_x',$("#yourElementId").scrollLeft());
$.cookie('scroll_y',$("#yourElementId").scrollTop());
});
$(document).ready(function() {
//restore scroll when the dom is ready
var x = $.cookie('scroll_x');
var y = $.cookie('scroll_y');
if( x != null ) $("#yourElementId").scrollLeft(x);
if( y != null ) $("#yourElementId").scrollTop(y);
});
Where the id of your element your want to scroll is "yourElementId".
The first step you need to take is getting the x/y components. You can achieve this by using elem.scrollTop and elem.scrollLeft. Record these to a local storage, detecting scroll using the onscroll event. Then, the next page load, assign the recorded x/y compontents to the elem.scrolLTop and elem.scrollLeft of the iframe.
var frame = document.getElementById("frame");
frame.contentWindow.addEventListener("scroll", function(){
sessionStorage.setItem("coordinates", this.scrollLeft + "," + this.scrollTop);
}, false);
window.addEventListener("load", function(){
if(sessionStorage.getItem("coordinates")){
var coordinates = sessionStorage.getItem("coordinate").split(",");
frame.scrollLeft = coordinates[0];
frame.scrollTop = coordinates[1];
}
}, false);
Note: untested and most likely guaranteed not to work without modifications to clean through errors.
Edit: I realized that the iframe doesn't handle onscroll, so you'd have to find a workaround for that...