HTML Why is the content of an Iframe loaded twice? - html

In my application I use a javascript function to set the src tag of an Iframe:
function loadDocument(id, doc) {
$("#DocumentContent").show();
$("#ButtonBox").show();
// Clear dynamic menu items
$("#DynamicMenuContent").html("");
$("#PageContent").html("");
// Load document in frame
$("#iframeDocument").attr("src", 'ViewDoc.aspx?id=' + id + '&doc=' + doc + '');
// Load menu items
$("#DynamicMenuContent").load("ShowButtons.aspx");
// Set document title
$("#documentTitle").load("GetDocumentInfo.aspx?p=title");
}
When I open Fiddler and debug this page, I notice that the 'ViewDoc.aspx' page is called twice.
When I put an alert() in the loadDocument function, I get only one alert message. In my viewdoc.aspx page there are no refresh or redirect statements or other statements that refreshes the page.
Is it possible this has something to do with browser? Is this default browser behavior?

the issue is pretty old, but....
do you have two elements with id=DynamicMenuContent ?
if there's one in the source page and one in the iframe, they may both be selected by $("#DynamicMenuContent").load...
if this is true and one is a div and the other a span, you could change it to $("div#DynamicMenuContent").load()...
hth

Related

Making a button to move an element from one html page to another html page

I wanted to take an image from one HTML file and when the user clicks a button, that image moves to a standard cell of a different HTML file.
To move an element between pages, if both pages are on the same domain, you can get the HTML of the element, put it in localStorage, then delete the element. On the other page, poll the localStorage for changes, the parse the element and use it in the DOM.
I wrote a set of functions to do that. On the sending page use this code. Call the function moveElement with the element you want to move to the other page.
const page="Your Page Name";
function moveElement(element){
const prefix="_elementmover_"+page+"_";
localStorage.setItem(prefix+"htmlToMove",element.outerHTML);
localStorage.setItem(prefix+"changedHtmlToMove",localStorage.getItem(prefix+"changedHtmlToMove")*1+1);
image.remove()
}
On the receiving page, use this code. The function receivedElement will be called wth the element.
const page="Your Page Name";
function receivedElement(element){
// Do whatever you want with the element here.
}
(()=>{
const prefix="_elementmover_"+page+"_";
let getChangeNum=()=>localStorage.getItem(prefix+"changedHtmlToMove")*1;
let oldChangeNum=getChangeNum();
let checkForChanges=()=>{
let newChangeNum=getChangeNum();
if(oldChangeNum!=newChangeNum){
let element=new DOMParser().parseFromString(localStorage.getItem(prefix+"htmlToMove"),"text/html").querySelector("html>body>*");
receivedElement(element)
}
oldChangeNum=newChangeNum
setTimeout(checkForChanges,100);
}
checkForChanges();
})();
Please note that the page variable should be unique on each set of pages it is on, but both pages must have the same value for it to work properly.

How to refresh a page and load at top after an anchor has been clicked, ignoring the anchor, and resetting back to the top?

I have a page with a few anchors. When a user clicks an anchor, the anchors work, and user is taken to the correct location.
If a user tries to refresh the page, it retains the anchor ID in the URL window and so naturally, when refreshing, it does not go back to the top of the page.
I think it would be more user friendly to go back to the top of the page on a refresh.
How would I achieve this?
My page currently is primarily using bootstrap, css, jquery, javascript, and php.
I think I need to set up some code so that after clicking the anchor, it removes the anchor from the url window, so that if someone refreshes, they'd be refreshing just the initial page state without an anchor, but I don't know how to begin. Or maybe I'm over thinking this and there's some way to always go to top of page on a refresh regardless of anchors or not. I'm not too code savvy.
Right now my code is like this...
An example of one of my anchors:
<a class="hoverlink" href="#firefighter"><li style="float:left; margin-right:1em; color:white; background-color:red" class="appao-btn nav-btn">Fire Fighter</li></a>
One of the elements for example that the anchor will jump to:
<div style="min-height:10px;" name="firefighter" id="firefighter" class="anchor"><p style="min-height: 10px;"> </p></div>
CSS style on my anchors:
.anchor:target { height:200px; display: block; margin-top:-2em; visibility: hidden;}
Actual Results With My Code: Page Refresh Stays At Anchor Location
Desired Results: Page Refresh Goes To Top Of Page
After some searching, I found a solution that almost works for me:
<script>
window.onbeforeunload = function () {
window.scrollTo(0, 0);
}
</script>
But it creates a flickering effect that doesn't look the best such as my example site at
https://graceindustries.com/gracetest/Grace%20Industries%20Website%20Design%202019%20Alternate%20Version/documentation.html
Anyone know how to remove the "flicker"?
You can try this (with the .some-anchor is the class for all a tag that points to some destinations within the page).
$('.some-anchor').click(function() {
var target = $(this).attr("href");
$('html, body').animate({
scrollTop: $("" + target).offset().top
}, 1000);
return false;
});
The "return false;" or preventDefault() event method will prevent the page from flickering. As I observed this does not make the # to the URL so refreshing is not a problem.
Other helpful answer: jQuery flicker when using animate-scrollTo
Navigating to page content using URL Fragments (#someLink) in anchor tags is a core part of the HTML specification. The standard implementation in most (if not all) web browsers is to add the fragment to the address bar. The fragment is part of the URL and therefore, when the page is refreshed the browser scrolls to the element with that ID. Most users will be familiar with this behaviour, even if they don't understand how or why it works like that. For this reason, I'd recommend not working around this behaviour.
However, if it is absolutely necessary, the only way to achieve the result you're looking for is to not use URL fragments for navigation and use JavaScript instead, therefore not putting the fragment in the URL in the first place. It looks like the Element.scrollIntoView() method might do what you're looking for. Rather than having
Click me
you'd use
<a onclick="document.getElementById('element1').scrollIntoView();">Click me</a>
or even better, implement this in an external JS file. If you experience issues due to the element not having the href attribute, you could always add an empty fragment href="#".
You can remove the id from the url right after the user click on the anchor tag
history.scrollRestoration = "manual" will set the scroll to the top of the page on refresh
<a onclick="removeAnchorFormURL()" href="#sec-2">here</a>
<script>
history.scrollRestoration = "manual";
const removeAnchorFormURL = () => {
setTimeout(() => {
window.history.replaceState({}, "", window.location.href.split("#")[0]);
}, 100);
};
</script>
window.location docs
location.href docs
location.replace docs
scrollRestoration docs (check it for info on scrollRestoration compatibility)

iframe with srcdoc: same-page links load the parent page in the frame

Same-page links work by referencing another element that has id="sec-id" on the same page, using
for instance. A link like this is relative.
However, if I use that very same syntax in the iframe in my LaTeX.js playground, it will not just scroll to the destination element, but (re)load the whole playground page inside the ifame. (Note that I set the contents of the iframe programmatically with iframe.srcdoc = html)
Example: LaTeX.js playground, right at the end of the first section click on the link in "See also SecĀ­tion 11." in the iframe on the right side.
What could be the reason?
UPDATE: I now understand the source of the problem: the browser uses the document's base URL to make all relative URLs absolute (see <base>). The trouble starts with an iframe that has its content set with srcdoc: no unique base URL is specified, and in that case the base URL of the parent frame/document is used--the playground in my case (see the HTML Standard).
Therefore, the question becomes: is there a way to reference the srcdoc iframe in a base URL? or is it possible to make the browser not prepend the base? or to make a base URL that doesn't change the relative #sec-id URLs?
I don't know exactly how you could resolve this, I think it is because the srcdoc, you can't use the src with the content-type because the character limit, but you can convert it to a Blob and it kinda works, the style are lost though. Maybe you can use it as a starting point, based on your page:
// Get the document content
const doc = document.querySelector('iframe').srcdoc;
// Convert it to blob
const blob = new Blob([doc], {type : 'text/html'});
// Load the blob on the src attr
document.querySelector('iframe').src = URL.createObjectURL(blob);
// Remove srcdoc to allow src
document.querySelector('iframe').removeAttribute('srcdoc');
What about catching the event and scrolling to the desired anchor?
$("a").click(function(e) {
$('.iframe').animate({
scrollTop: $(e.target.attr('href')).offset().top
}, 2000);
return false;
});
For the record, it seems that my question is not possible, i.e., it is not possible to use relative same-page links in an iframe that has its content set using srcdoc. A workaround has to be used, see the other answer.

How do I link to mid-page content that's already inside a mid-page link?

I'm making a page that has 4 in-page tabs on it. To link to those tabs, the URL is
URL/#tab-1-tab; URL/#tab-2-tab etc
Now, in one of the tabs I want to have buttons that link to specific points on a page inside another tab, but not sure if it's actually possible to link to.
I've made the anchors on that page with
<a name="1"></a>
But I can't figure out how to link to them. I tried
URL/#tab-4-tab/#1 and URL/#tab-4-tab#1
Not sure what else to try. The links do work if I go to the tab with the anchors, then erase the tab url bit and just put in the anchor link, so instead of
URL/#tab-4-tab, I type in URL/#1
Then it jumps to the right point.
But that doesn't work if I'm on any other tab or page.
Is it possible to do this somehow?
If your using tabs to switch div CSS properties like display:none / display:block then you will need some jQuery / JavaScript to switch them based of URL no differently then your jQuery that listens for the tabs "onclick" event then shows that relative div.
First step would be to obtain a JavaScript URL reader that listens for variables or hashtag-bookmarks. Here is an example of a variable reader I have used before.
http://jsfiddle.net/googabeast/hhkuj/
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
//usage
var myVar = getUrlVars()["tab"];
That would make the URL format slightly different then your above posting, something more like "index.php?tab=2" / "index.php?tab=3" etc...
Next phase would be generate a switch based off the incoming URL variables to properly show the requested div.

How to make tabs on the web page?

How to make tabs on the web page so that when click is performed on the tab, the tab gets css changed, but on the click page is also reloaded and the css is back to original.
dont use the jquery :D
all of what you needs a container, a contained data in a varable and the tabs
the container is the victim of the css changes.
the tabs will trigger the changing process.
if you have a static content, you can write this into a string, and simply load it from thiss.
if you have a dinamically generated content, you need to create ajax request to get the fresh content, and then store it in the same string waiting for load.
with the tabs you sould create a general functionusable for content loading.
function load(data) {
document.getElementById("victim").innerHTML = data;
}
function changeCss(element) {
//redoing all changes
document.getElementById("tab1").style.background="#fff";
document.getElementById("tab2").style.background="#fff";
element.style.background = "#f0f";
}
with static content the triggers:
document.getElementById("tab1").onclick = function() {load("static data 1");changeCss(document.getElementById("tab1"))};
document.getElementById("tab2").onclick = function() {load("static data 2");changeCss(document.getElementById("tab2"))};
if you want to change the css, you need another function which do the changes.
i tell you dont use the jquery because you will not know what are you doing.
but thiss whole code can be replaced by jquery like this:
$("tab1").click(function(e) {
$("#tab1 | #tab2").each(function() {
$(this).css("background","#fff"); });
$(this).css("background","#00f");
$("#victim").append("static content 1");
});
$("tab12click(function(e) {
$("#tab1 | #tab2").each(function() {
$(this).css("background","#fff"); });
$(this).css("background","#00f");
$("#victim").append("static content 2");
});
if you know how javascript works then there is noting wrong with the jquery, but i see there is more and more people who just want to do their website very fast and simple, but not knowing what are they doing and running into the same problem again and again.
Jquery UI Tabs:
http://jqueryui.com/demos/tabs/
Have a <A href tag around the "tab" and use onClick to fire some Javascript that changes the CSS.
If you do not want use Jquery for creating of UI tabs, please see my cross-browser JavaScript code: GitHub.
You can use different ways to create tabs and tab content.
Tab content can added only when tab gets focus.
You can remember selected tab. Selected tab opens immediatelly after opening of the page.
You can create tabs inside tab.
Custom background of the tab is available.
Example: Tabs