My website - https://wilfredopersonal.herokuapp.com/# - shows some specific content for mobile view. The problem is that this content is also shown in Desktop while the Desktop content is loading. How can I prevent it from doing so?
<script>
function isMobile() {
if (navigator.userAgent.match(/Mobi/)) {
return true;
}
if ("screen" in window && window.screen.width < 1366) {
return true;
}
var connection =
navigator.connection ||
navigator.mozConnection ||
navigator.webkitConnection;
if (connection && connection.type === "cellular") {
return true;
}
return false;
}
</script>
<script>
if (!isMobile()) {
document.getElementById("not-desktop").style.display = "none";
document.getElementById("container").style.display = "unset";
} else {
document.getElementById("not-desktop").style.display = "unset";
document.getElementById("container").style.display = "none";
}
</script>
Because your script is executed after HTML loaded. So before the browser read to your script, the mobile keep visible.
I recommend you to use CSS media query to solve this rather then using script. Here is a good answer demonstrate how to use media query to target desktop and mobile. This answer could solve your problem.
Another way is set #not-desktop's display to none in your CSS. Then when the script executed, if it is shows on mobile, your code will show it. But this method is not flexible.
This is an issue where you are displaying both your mobile view and your desktop view at the same time, then disabling which ever "view" is incorrect. Since your javascript is loaded after the page is created, it will display both views until the javascript loads and disables one.
You can fix this by making both of them "disabled" from the start - add the style attribute like this: style="display:none" to "not-desktop" and "container". That way both of them will be disabled until the javascript can enable one.
EDIT: after looking at Li Jinyao's answer, I see that there is a much faster way to do this - use a CSS media tag to check the width of the element, and only display it if it matches the requirements. Afterwards, use java script to check the userAgent and anything else, and change the displayed element accordingly.
To see information about CSS media tags, look at Li Jinyao's answer.
How can I control the background image and colour of a body element within an iframe? Note, the embedded body element has a class, and the iframe is of a page that is part of my site.
The reason I need this is that my site has a black background assigned to the body, and then a white background assigned to divs that contain text. A WYSIWYG editor uses an iframe to embed content when editing, but it doesn't include the div, so the text is very hard to read.
The body of the iframe when in the editor has a class that isn't used anywhere else, so I'm assuming this was put there so problems like this could be solved. However, when I apply styles to class.body they don't override the styles applied to body. The weird thing is that the styles do appear in Firebug, so I've no idea what's going on!
Thanks
UPDATE - I've tried #mikeq's solution of adding a style to the class that is the body's class. This doesn't work when added to the main page's stylesheet, but it does work when added with Firebug. I'm assuming this is because Firebug is applied to all elements on the page whereas the CSS is not applied within iframes. Does this mean that adding the css after window load with JavaScript would work?
The below only works if the iframe content is from the same parent domain.
The following code works for me. Tested on Chrome and IE8. The inner iframe references a page that is on the same domain as the parent page.
In this particular case, I am hiding an element with a specific class in the inner iframe.
Basically, you just append a style element to the head section of the document loaded in a frame:
frame.addEventListener("load", ev => {
const new_style_element = document.createElement("style");
new_style_element.textContent = ".my-class { display: none; }"
ev.target.contentDocument.head.appendChild(new_style_element);
});
You can also instead of style use a link element, for referencing a stylesheet resource.
An iframe is a 'hole' in your page that displays another web page inside of it. The contents of the iframe is not in any shape or form part of your parent page.
As others have stated, your options are:
give the file that is being loaded in the iframe the necessary CSS
if the file in the iframe is from the same domain as your parent, then you can access the DOM of the document in the iframe from the parent.
You cannot change the style of a page displayed in an iframe unless you have direct access and therefore ownership of the source html and/or css files.
This is to stop XSS (Cross Site Scripting)
This code uses vanilla JavaScript. It creates a new <style> element. It sets the text content of that element to be a string containing the new CSS. And it appends that element directly to the iframe document's head.
Keep in mind, however, that accessing elements of a document loaded from another origin is not permitted (for security reasons) -- contentDocument of the iframe element will evaluate to null when attempted from the browsing context of the page embedding the frame.
var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
'body {' +
' background-color: some-color;' +
' background-image: some-image;' +
'}'
;
iframe.contentDocument.head.appendChild(style);
Override another domain iframe CSS
By using part of SimpleSam5's answer, I achieved this with a few of Tawk's chat iframes (their customization interface is fine but I needed further customizations).
In this particular iframe that shows up on mobile devices, I needed to hide the default icon and place one of my background images. I did the following:
Tawk_API.onLoad = function() {
// without a specific API, you may try a similar load function
// perhaps with a setTimeout to ensure the iframe's content is fully loaded
$('#mtawkchat-minified-iframe-element').
contents().find("head").append(
$("<style type='text/css'>"+
"#tawkchat-status-text-container {"+
"background: url(https://example.net/img/my_mobile_bg.png) no-repeat center center blue;"+
"background-size: 100%;"+
"} "+
"#tawkchat-status-icon {display:none} </style>")
);
};
I do not own any Tawk's domain and this worked for me, thus you may do this even if it's not from the same parent domain (despite Jeremy Becker's comment on Sam's answer).
An iframe has another scope, so you can't access it to style or to change its content with javascript.
It's basically "another page".
The only thing you can do is to edit its own CSS, because with your global CSS you can't do anything.
This should work with cross domain if you're the owner of the both
The trick here is to assign a global css variable to your body, to listen message with the new color, and then to change the global css variable once receive a message.
I'm using angular, but it should work with pure javascript
My use case was to show to the user what he how the color change would impact his website in the iframe before saving it
Domain A
#ViewChildren('iframeContainer') iframeContainer: QueryList<ElementRef>
sendDataToIframe(
data = {
type: 'colorChange',
colors: {primary: '#000', secondary: '#fff'},
},
): void {
if (this.targetUrl)
this.iframeContainer.first.nativeElement.contentWindow.postMessage(data) // You may use document.getElementById('iframeContainer') instead
}
Domain B
acceptedEditOrigins = [
'https://my.origine.ccom', // Be sur to have a correct origin, to avoid xss injecto: https://en.wikipedia.org/wiki/Cross-site_scripting
]
constructor() {
// Listen to message
window.addEventListener('message', (event) => this.receiveMessage(event), false)
}
receiveMessage(event: MessageEvent) {
if (this.acceptedEditOrigins.includes(event.origin))
switch (event.data.type) {
case 'colorChange': {
this.setWebsiteConfigColor(event.data.colors)
}
}
}
setWebsiteConfigColor(colors: WebsiteConfigColors) {
if (colors) {
const root = document.documentElement
for (const [key, value] of Object.entries(colors)) {
root.style.setProperty(`--${key}`, value) // --primary: #000, --secondary: #fff
}
}
}
body {
background-color: var(--primary);
}
If you have control of the page hosting the iframe and the page of the iframe, you can pass a query parameter to the iframe...
Here's an example to add a class to the iframe based on whether or not the hosting site is mobile...
Adding iFrame:
var isMobile=$("mobile").length; //detect if page is mobile
var iFrameUrl ="https://myiframesite/?isMobile=" + isMobile;
$(body).append("<div id='wrapper'><iframe src=''></iframe></div>");
$("#wrapper iframe").attr("src", iFrameUrl );
Inside iFrame:
//add mobile class if needed
var url = new URL(window.location.href);
var isMobile = url.searchParams.get("isMobile");
if(isMobile == "1") {
$("body").addClass("mobile");
}
For juste one iframe, you can do something like this:
document.querySelector('iframe').contentDocument.body.style.backgroundColor = '#1e1e2d';
In case you have multiple iframe you're dealing with:
document.querySelectorAll('iframe').forEach((iframe) => {
iframe.contentDocument.body.style.backgroundColor = '#1e1e2d';
});
Perhaps it's changed now, but I have used a separate stylesheet with this element:
.feedEkList iframe
{
max-width: 435px!important;
width: 435px!important;
height: 320px!important;
}
to successfully style embedded youtube iframes...see the blog posts on this page.
give the body of your iframe page an ID (or class if you wish)
<html>
<head></head>
<body id="myId">
</body>
</html>
then, also within the iframe's page, assign a background to that in CSS
#myId {
background-color: white;
}
I have this js code I searched on auto-resizing iframe height with its content. It does what the user who posted this says it does. However, I now have this problem with dynamic content within the iframe.
The js code I have works only with the regular content of the page but not when there are dynamic changes going on within. For example, displaying texts through ajax call.
I've tried searching for other solutions to this but others did not work as well as what this code can do.
I'm hoping that there's someone who could help me update the code to meet what I currently need. I'm not very familiar with jquery/javascript to do this on my own. Thank you in advance! :)
This is the JS code:
function setIframeHeight(iframeId) {
var ifDoc, ifRef = document.getElementById(iframeId);
try {
ifDoc = ifRef.contentWindow.document.documentElement;
} catch (e) {
try {
ifDoc = ifRef.contentDocument.documentElement;
} catch (ee) {}
}
if (ifDoc) {
ifRef.height = 1;
ifRef.height = ifDoc.scrollHeight;
/* For width resize, enable below. */
//ifRef.width = 1;
//ifRef.width = ifDoc.scrollWidth;
}
}
I found this other code which enables iframe adapting to its dynamic content but I do not know how to make the code above and this work together. Please help me.
var iframe = document.getElementById("ifr").contentWindow;
iframe.$(".toggle_div").bind("change", function () {
$("#ifr").css({
height: iframe.$("body").outerHeight()
});
});
To summarize, I need a code that autoresizes iframe with its content and will autoresize again if there are changes on the size of the content.
The problem is that your page doesn't have any trigger indicating to resize when the iframe body resizes.
There also (as far as I know) isn't anything built into javascript that lets you watch for changes in an elements height.
You have two options.
If you are the owner of the iframe content, you can put a script in that page which can call to it's parent window telling the parent to run your resize script, or you can run a function which checks for changes say every second or so.
For the first method, you can follow the answer from here Can events fired from an iframe be handled by elements in its parent?
Otherwise just do a
setTimeout(function(){
$("#ifr").css({
height: iframe.$("body").outerHeight()
});
},1000);
function adjustMyFrameHeight()
{
var frame = getElement("myFrame");
var frameDoc = getIFrameDocument("myFrame");
frame.height = frameDoc.body.offsetHeight;
}
call this method on your iframe onload event and replace mtFrame to your iframe Id
When I launch my page, the css is totally messed up because my js is supposed to dynamically load css on click (mobile or standard website css). Currently, it just loads them both. Here's the code:
function loadjscssfile(filename, filetype)
{
if (filetype=="css")
{
var fileref = document.createElement("link");
fileref.rel= "stylesheet";
fileref.type = "text/css";
fileref.href = filename;
document.getElementsByTagName("head")[0].appendChild(fileref)
}
}
loadjscssfile("HCSS.css", "css")
I have two links on the site. One loads the mobile css, the other loads the standard website css. I have it linked like this:
load hcss
<br/>
load mobile
What you are after is swapping css files, not just loading a new one. In jquery it would probabaly look something like this (code not tested):
function swapCssFiles(fileToLoad, fileToUnload) {
$('head link[href="'+fileToUnload'"]') // select the tag with css to unload
.attr('href', fileToLoad); // swap the href attribute with the file to load
}
This is off course possible with 'pure' javascript, but I'm to much a jQuery addict to tell you how. If you see how easy the syntax is, you can probably tell why.
Your links would look something like this:
load hcss
I hope this is helpfull.
Note however that this is not the way I would approach this. If you want to target mobile devices with specific css, I would use mediaqueries to detect screensize, and not javascript.
I am attempting to apply CSS to a document that I'm loading into an iFrame. I am using the OK_loadit function as follows:
function OK_loadit(url,layerObjNS, width) {
if (document.layers){
document.layers[layerObjNS].load(url, width);
} else{
if (window.frames.length > -1){
window.frames[layerObjNS].location.href = url;
}
The document I am loading into the iFrame is a php Seresnipity blog page.
The blog page's CSS needs to be set to "background= #000000", so that it can be viewed from links in the RSS feed with a black background. That's already done.
But when the blog page is rendered in it's iFrame on my website (which is located on the same domain as the blog), it's CSS needs to be set to "background= transparent".
Is there any way to modify the OK_loadit script above in such a way that I can reset the background parameter of the page accordingly when it's loaded into the iFrame, or do I need to use a different script altogether?
Either way, I'd really appreciate it if someone here could hook me up with what I need.
Thanks!
James
[edit]
deleted previous answer
[/edit]
sorry, I re-read your question and realized that the solution is easier than I had thought.
in the url that you're passing to this page just add ?tran to the url string..
so...
"myPage.php?tran"
then in the php page add this...
<script>
document.onload = function(){
if(self.location.query.indexOf("?tran") == 0)
document.bgColor = "transparent"
}
</script>
I think that should work.