I have a page, https://einsteinmedneuroscience.org/wp-content/scroll/master.html# with two undisplayed iframes. There is a little arrow button for each one of them to trigger them to display. The iframes are long, so neither of them will fit on the page, and the page itself gets a vertical scroll bar. (This is the intended effect.)
First, click the top button to display the first iframe.
Second, scroll to the bottom of the page and now click the second button.
Two things happen, the second iframe appears and the whole page is spontaneously scrolled back to the top of the page. What on Earth has caused that and is there a way to prevent it (to keep the second iframe in view)?
Here's the code on this page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
function observeIFrameChange(mutations){
for (let mutation of mutations) {
if (mutation.oldValue = "display:none") {
mutation.target.style.height = `${mutation.target.contentWindow.document.body.scrollHeight}px`;
}
}
}
$(document).ready(function () {
function buttonClickFunction() {
/* swap the arrow icon when clicked */
var theCurrentCharacter = this.innerHTML;
var theClickedAnchorTag = document.getElementById(this.id);
var theIFrameTag = document.getElementById(theClickedAnchorTag.dataset.tag);
if (theCurrentCharacter === "·?") {
this.innerHTML = "??";
/* when the iframe is displayed, by default it displays 150 pixels height. */
/* to assign its actual height, we need to set up a mutation observer for attribute changes */
/* because for whatever reason, it won't work here */
var observer = new MutationObserver(observeIFrameChange);
observer.observe(theIFrameTag, { attributes: true, childList: false, attributeOldValue: true });
/* display the iframe */
theIFrameTag.style.display="inline";
} else {
this.innerHTML = "·?";
theIFrameTag.style.display="none";
}
}
/* assign buttonClickFunction to little arrow buttons */
var theBtnRow1 = document.getElementById("btn_row1");
var theBtnRow2 = document.getElementById("btn_row2");
theBtnRow1.addEventListener("click", buttonClickFunction);
theBtnRow2.addEventListener("click", buttonClickFunction);
Note that the HTML for the button element was like so
<a id='btn_row1' href="#" class="buttonshape" data-tag="firstiframe">➡︎</a>
This was where the error was.