Changing viewport/screen width js - javascript

I've been trying to build a responsive button on our new website which changes the body width to 460px for example to show what our website looks like on mobile. I've seen this done using iframes as the iframe width sets the viewport width so a button can set a width of the iframe and it will change and look responsive.
I'm trying to do this with vanilla javascript but struggling. I can set the body width no problem, but bootstrap and the css media queries don't respect setting a width as it works off of viewport/screen width which remains the same.
How do I do this? I have a button of a mobile, and a button of a desktop and they should adjust the screens width to mobile/desktop widths and the media queries should respect it.
Is this possible? My viewport is set as:
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
and media queries as:
#media screen and (min-width: 992px) {}

If I don't get you wrong about your case, I have 2 recommend for you.
Use function open to open the new window that is fully loaded in desired width and height. You can take a look at here
var option_string = "location=yes,width=640,scrollbars=yes,status=yes";
var URL = "https://your_link.com";
var win = window.open(URL, "_blank", option_string );
Instead of loading your full page, use iframe of page which you want to display and embed, after click Desktop or Mobile button, change the width of iframe depend on which button is clicked. Take a look at example below for more details:
<body>
<iframe id="your_site" src="https://your_link.com">
<button class="btn btn_desktop">Desktop</button>
<button class="btn btn_mobile">Mobile</button>
<script>
var $iframe = document.getElementById('your_site');
var $resize_button = document.getElementByClass('btn');
$resize_button.on('click', function(e){
var $button = e.target;
if (button.classList.contains('btn_desktop')) { // bigger your frame
$iframe.style.width = '640px';
} else {
$iframe.style.width = 'auto';
}
})
</script>
</body>
Hope it would help

Related

How to redirect to another page at a breakpoint?

I have to redirect to another webpage at a breakpoint of 800px
I have tried the below code and tried in incorporate at a breakpoint, but it was always redirecting even at the above breakpoints
<meta http-equiv="refresh"
content="2;
url=http://redirectedSite.com/">
needed to make the page to be redirected to another page at a breakpoint using HTMl or JS
You can do this with plain javascript. Add an Event Listener for browser resize and check for browser window width and redirect.
window.addEventListener('resize', screen_resize);
function screen_resize() {
var h = parseInt(window.innerHeight);
var w = parseInt(window.innerWidth);
if(w <= 800) {
window.location.replace("http://redirectedSite.com/");
}
}
Not tested but I think this javascript code should work:
<script type="text/javascript">
if (screen.width > 800) {
window.location.replace("http://redirectedSite.com");
}
</script>
Please note that this redirecting is bad practice.
If this is for getting a different screen layout you should just change your layout using css.
You could use #media (min-width: 800px) { your css } to only effect users using larger devices.

How to change href and onclick function of a download button based on device width

I am wanting to change the download link based on a device width (mobile, tablet, pc) What js would I need to accomplish this?
Download
In this answer you learn that there are many method of obtaining the device width in js. One of the best them is the one below:
const mq = window.matchMedia( "(min-width: 500px)" );
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
So you can do something like (resize window to test for small size):
var a_element;
function changeHref() {
const mq = window.matchMedia( "(min-width: 500px)" );
a_element = document.querySelector(".download");
if (mq.matches)
a_element.href = "http://www.google.com";
else
a_element.href = "http://www.duckgogo.com";
}
changeHref();
console.log(a_element.href);
Download
Dont use width in javascript. Have 3 anchor tags, show only 1 at once using media queries width
<a onclick="function1()"; class="showOnDesktopOnlyUsingMediaQuery">Download Desktop</a>
<a onclick="function2()"; class="showOnTabletOnlyUsingMediaQuery">Download Tablet</a>
<a onclick="function3()"; class="showOnMobileOnlyUsingMediaQuery">Download Mobile</a>
You can accomplish without even using JavaScript. CSS Media Queries are designed exactly for this type of thing. You make 3 separate <a> tags, and alternate between display:inline or display:none based on the media queries. For example, on a mobile screen, both the desktop and tablet links will be set to display:none while the mobile link will be set to display:inline.
But if you really need to use JS though, you can do something like the following.
HTML:
Download
JavaScript:
var link = document.getElementById("link-change");
var mobile = "url-mobile";
var tablet = "url-tablet";
var desktop = "url-desktop";
link.onclick = function(){
if(screen.width < 768){
link.href = mobile;
} else if(screen.width < 1024){
link.href = tablet;
} else {
link.href = desktop;
}
}
You may need to change the breakpoints (1024px, 768px) I just used those off the top of my head for this example.

React Page Getting Weird Scaling in Responsive Mode [duplicate]

When in google chrome's device mode, what does window.innerWidth return? Is it the viewport of the device (plus any scroll bars)?
I'm getting different values for the device's width x height (the dimensions on top of the page - the device's viewport?) and window.innerWidth x window.innerHeight (browser's viewport?). Is this supposed to happen?
Here's a picture of what I'm getting, and the code I used.
<!doctype html>
<html>
<head></head>
<body>
<script>
var image;
window.onload = function() {
image = document.getElementById("img");
checkWindowSize();
window.addEventListener('resize', function(event){
checkWindowSize();
});
}
function checkWindowSize() {
var width = window.innerWidth,
height = window.innerHeight;
console.log("window.innerHeight: ", window.innerHeight, " window.innerWidth: ", window.innerWidth);
}
</script>
<img id="img" class="vid-img-filter" src="http://i.imgur.com/jkhFJMn.jpg" alt="">
</body>
</html>
window.innerWidth and innerHeight return the dimensions of the visual viewport. In desktop browsers, this is generally the browser's window dimensions. On mobile the situation is a bit more complicated because of pinch zoom.
When you load a page without a <meta name="viewport"> tag, a default layout width is used (e.g. Chrome uses 980px). When the browser loads the page it does so maximally zoomed out. It looks like your device size above has a width of 425px so the browser zooms out when the page is loaded to see the whole 980px. If you have content that's wider than this (e.g. your image) it'll zoom out even further. Seeing as how your window.innerWidth is 1248, that implies a scale factor of about 30%.
tl;dr: innerWidth/innerHeight reflect viewport with the pinch-zoom factor applied and the page is loaded fully zoomed out.
EDIT: This has since changed in Chrome. window.innerWidth now returns the layout viewport width. To get the visual viewport width, use window.visualViewport.width. See this article for more details.
I'm not sure if this is a recent update (since the last responses), but I was able to find the viewport height/width by using:
window.screen.width
and
window.screen.height
This was particularly useful when I was trying to test whether the screen was phone-sized or not.
We're currently having success with something like:
const widths = [window.innerWidth];
if (window.screen?.width) {
widths.push(window.screen?.width);
}
const width = Math.min(...widths);
The conditional check is there because I'm not sure how widespread the screen width API is. You may need to adjust this not to use certain newer JS features depending on what devices you are targeting/your build process.
This could potentially go a bit weird if you have a window that is wider than the screen, but for us that isn't a problem.
This gives us a width that matches the one at the top of the Responsive screen tool, even when contents overflow horizontally. This is important for us because we needed the UI to change in order to prevent that overflow, but the overflow was interfering with the width number we used to trigger the adjustment.
I'm not sure if this is important, but we are also using:
<meta name="viewport" content="width=device-width, initial-scale=1" />

Net width and net height of current browser

I try to build a web application that will fit with almost all sizes of devices/browsers. To do so, my actual approach is to define,inside of my body, a div that will take the whole space of body:
#mydiv {
width: 100%;
height: 100%;
}
I calculate, then, width and height of my available space using:
var Width= $("#mydiv").width();
var Height= $("#mydiv").height();
I do what I want after. I position my elements with jQuery/CSS (percentages, top property, absolute positionnong,...), I draw with Rapahael.js....
I discovered that this approach is not always efficient, especially for browsers that display their addons as HTML. For example in my Chrome, when I install a toolbar addon, this toolbar is rendered in the page code source as HTML elements with their own styles (top=0, fixed postion..). The consequence is that all my work with top position is shifted by the height of the toolbar.
How can I calculate the net height of body?
What are alternative approaches to create webpage that adapts with the net browser size (I mean after any DOM injected elements outside of my control like ask.com toolbar... )?
Edit: so I gave this problem a little thought and I figure that if an add-on is going to draw to the DOM, it's most likely going to append itself to body. So, if you structured your document body in this manner:
<body>
<div id="container">
... all your content here
</div>
</body>
and the add-on inserted itself like this:
<body>
<div id="toolbar" style="margin:0;padding:5px;position:fixed;top:0px;left:0px;width:100%;height:20px;background-color:#000;color:#fff">toolbar</div>
<div id="container">
... all your content here
</div>
</body>
You could overcome this by setting #container's position to relative and adding the following script to your page:
var shift_amount = 0;
var children = document.body.children;
for(var i = 0; i < children.length; i++){
if(children[i].style.position == 'fixed'){
shift_amount += parseFloat(children[i].style.height);
}
}
var Height = $(window).height();
var Width = $(window).width();
if(shift_amount > 0){
// subtract fixed element height from available height
Height -= shift_amount;
}
As I'm pretty sure the question #RoryMcCrossan linked answers the question you asked, I will add that the preferred approach to creating responsive websites is to use media queries to adapt your CSS at various widths (mobile, tablet, desktop). Here is an example of media queries in action using Twitter Bootstrap, open that page and resize your browser window.
<style>
/* target only browsers less than or equal to 600px; */
#media (max-width: 600px) {
.sidebar {
display: none;
}
}
</style>
Regarding the issue of having toolbars and other components rendered in the HTML, this is going to be difficult to overcome as you can't know any and every element that will get injected into the DOM outside of your control. If you are targeting a specific use case, please point us to that add-on and there may be a solution to find.
I would take a look at the "mutation observers" to detect changes in the DOM structure.
Then you can just get those values again.
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
Width= $("#mydiv").width();
Height= $("#mydiv").height();
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});

Ad image in full screen for mobile devices without scrollbar

I would like to create an HTML/CSS/Javascript page that can show a picture (an ads) in full screen for mobiles. Smartphones + tablets. The ads stretch to the maximum width and height and there is no scrollbar.
I try two diferent ways :
var screenWidth = $(window).width();
var screenHeight = $(window).height();
$('body, .ads-picture').css('width', screenWidth+'px');
$('body, .ads-picture').css('height', screenHeight+'px');
And in other way with media queries for each devices.
But it doesn't work in any situation. In iPhone 5 the picture is not in full screen (I need to scroll), in iPad mini also.
Can you help me please ? Thanks !!!
add the following tag and put width: 100% im the images
<meta name="viewport" content="width=device-width, user-scalable=no">
get more info about it here

Categories

Resources