how to reset style that changed by using javascript - javascript

I am trying to make a full RWD webpage using HTML5, CSS3, and JavaScript.
I have used #media in my CSS stylesheet file to set aside width:0; and hidden overflow, in small devices. I added a button that calls java scripts to minimize article and maximize aside menu, and another button to minimize aside and return article.
The following code is called:
function openaside() {
document.getElementById("article").style.width = "0";
document.getElementById("aside").style.width = "100%";
document.getElementById("showasidebtn").style.width = "0";
document.getElementById("hideasidebtn").style.width = "25pX";
}
function closeaside() {
document.getElementById("article").style.width = "100%";
document.getElementById("aside").style.width = "0";
document.getElementById("showasidebtn").style.width = "25px";
document.getElementById("hideasidebtn").style.width = "0";
}
My page correctly responds to screen size and my scripts work fine. However when I use these scripts to change style and then change screen size, my article and aside width do not dynamically change until I refresh the page.
I have added the following JavaScript code to refresh page when screen is resized:
window.addEventListener("resize", onresize);
function onresize(){
location.reload(false)
}
Thanks every one I Find a way, instead of
function onresize(){
location.reload(false)
}
I use:
function onresize(){
document.getElementById("article").style.width = "";
document.getElementById("aside").style.width = "";
document.getElementById("showasidebtn").style.width = "";
document.getElementById("hideasidebtn").style.width = "";
}
But article minimize when the screen is moved in phones (e.g. scrolling). So now phone users should first scroll then open side menu. Could you help me find a better way? Is there any way to call a script when screen width exceed a certain amount?

I seems in java script we don't have independent event listener for screen size. But I realized we can get screen size, so I use following code:
function onresize() {
window.addEventListener("resize", onresize);
var viewportwidth;
// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight
if (typeof window.innerWidth != 'undefined') {
viewportwidth = window.innerWidth
}
//then I checked size to reset if nesecery
if (viewportwidth > 600) {
document.getElementById("article").style.width = "";
document.getElementById("aside").style.width = "";
document.getElementById("showasidebtn").style.width = "";
document.getElementById("hideasidebtn").style.width = "";
}
JAVA SCRIPT IS AMAZING.
Thanks all.

Related

Javascript column resizing only working when page is refreshed

Hi — I've inherited a website that has a little javascript script that isn't working properly. I didn't code it myself and am a javascript n00b, so please forgive my ignorance.
The site switches from 3-column view to 1-column view depending on window size, and there's a script to make one particular section of the site convert neatly between the two views (by setting the column heights such that they stack neatly). I've noticed that if I resize the window without refreshing, the column heights fail to adjust. How can I fix this?
Thanks!
<script type="text/javascript">
function adjust_col_heights() {
if (window.innerWidth > 991) {
var col_1_height = document.getElementById('col-1').clientHeight;
var col_2_height = document.getElementById('col-2').clientHeight;
var col_3_height = document.getElementById('col-3').clientHeight;
console.log("adjusting heights from:", col_1_height, col_2_height, col_3_height);
var col_max_height = Math.max(Math.max(col_1_height, col_2_height), col_3_height);
var css_height = col_max_height + "px";
document.getElementById('col-1').style.height = css_height;
document.getElementById('col-2').style.height = css_height;
document.getElementById('col-3').style.height = css_height;
document.getElementById('poem').style.position = "absolute";
}
else {
document.getElementById('poem').style.position = "relative";
}
}
adjust_col_heights();
window.onresize = adjust_col_heights;
</script>
window.onload = function () {
resizeElements();
window.addEventListener('resize', resizeElements);
}
function resizeElements() { ... }

getComputedStyle width and height not working in chromium webview on real Android devices

I had this javascript function:
function onFontLoad(cb,font,size,table,interval)
{
var div=document.createElement("div");
div.style.fontFamily=font;
div.style.fontSize=size;
div.style.position="absolute";
div.style.top="-100px"
div.style.left="-100px"
document.body.appendChild(div);
var checkInterval=setInterval(function()
{
for(character in table)
{
div.textContent=character;
var t=table[character];
var s=getComputedStyle(div);
if(parseInt(s.width)!=t[0]||parseInt(s.height)!=t[1]) return;
}
div.parentNode.removeChild(div);
clearTimeout(checkInterval);
cb();
},interval||200);
And it worked since webview in android was based on webkit.
Since WebView was changed to chromium my function stop working even in Chromium browser. I got suggestion to use Math.ceil with rounding, and also avoid using parseInt.
Now I have this function:
function onFontLoad(cb, font, size, table, interval) {
var div = document.createElement("div");
div.style.fontFamily = font;
div.style.fontSize = size;
div.style.position = "absolute";
document.body.appendChild(div);
var getRawPixels = function (cssUnit) {
// Round up to the highest unit.
var re = /([\d.]+)(px)/; // css measure units.
var results = cssUnit.replace(re, "$1");
return Math.ceil((results * 10) / 10) ;
};
var checkInterval = setInterval(function () {
for (var character in table) {
div.textContent = character;
var t = table[character];
var s = getComputedStyle(div);
if (getRawPixels(s.width) != t[0] || getRawPixels(s.height) != t[1]) return;
}
div.parentNode.removeChild(div);
clearTimeout(checkInterval);
cb();
}, interval || 200);
And function works like intended now in Chromium browser or in Android (starting 4.4 to 6 emulators) and I have no problem with webview rendering in emulators. But its blank on some real devices, even without webview hardware acceleration.(mostly android 5.x devices) But I'm pretty there is no problem with canvas rendering, since if I comment or remove this string:
if (getRawPixels(s.width) != t[0] || getRawPixels(s.height) != t[1]) return;
Webview will start render as intended again even with real android devices I test application with, but without applying style from onFontLoad function.
Another thing I found in process is that broken webview in Chrome Developer Tools adds <i> after div. But same code running in emulator displaying canvas nicely and there no any <i> after div. However I can broke canvas in emulator if I remove string with div position. And after this doom action I'll see <i> in page source code after div too.
Also, I found that Chromium had some issues with getComputedStyle in past too. But I think getComputedStyle is working ok.
It was something with div hiding. I just removed hiding, since after hiding div destroyed itself with application in canvas. Simplicity really a key there.
function onFontLoad(cb, font, size, table, interval) {
var div = document.createElement("div");
div.style.fontFamily = font;
div.style.fontSize = size;
//div.style.position = "relative";
document.body.appendChild(div);
var checkInterval = setInterval(function () {
for (var character in table) {
div.textContent = character;
var t = table[character];
var s = getComputedStyle(div);
}
clearTimeout(checkInterval);
cb();
}, interval || 200);
}

jQuery window width not equal to CSS's window width

I'm using the following two pieces of CSS and JS code:
#media (max-width: 720px) {
// a code to make arrows in a carousel disappear
}
if(jQuery(window).width() <= 720){
// a code to make arrows in the carousel stop working
}
The problem with them is that the latter executes on exactly width=738px and not 720px. I suspect that this is because of browser's vertical scrollbar that has width equal to 18px in Chrome.
Is there a way to unify this? I'd like these actions to happen at the same moment in all browsers regardless of the scrollbar's width.
Tests (when browser is # 720px and CSS has already executed):
jQuery(document).innerWidth() = 703
jQuery(window).innerWidth() = 703
jQuery(document).width() = 703
jQuery(window).width() = 703
jQuery('body').width() = 703
jQuery('html').width() = 703
I had to tackle the same problem a while ago, and so far the most correct solution I found is to use media queries to pass the actual window size to Javascript. You have to follow these steps:
Add a hidden element to your page,
Use media queries to alter the max-width property of that element,
Read back the max-width property of that element through Javascript.
For instance, add the following element to your page:
<div id="currentMedia"></div>
Then write the following CSS rules:
#currentMedia {
display: none;
}
#media (max-width: 720px) {
/* Make arrows in the carousel disappear... */
#currentMedia {
max-width: 720px;
}
}
Then, from the Javascript side, you can write:
if (parseInt(jQuery("#currentMedia").css("max-width"), 10) <= 720) {
// Make arrows in the carousel stop working...
}
And it will be accurate regardless of the scrollbar size, since the value comes from the same media query that triggers the carousel's disappearance.
I tested this solution on all major recent browsers, and it gives correct results.
You will find the big summary of what properties are supported on what browsers on this page on quirksmode.org.
Your best bet is probably to grab an element in the page (using document.body where supported, or document.getElementById or whatever), walk its offsetParent chain to find the topmost element, then examine that element's clientWidth and clientHeight.
innerWidth documentation
innerWidth() says this method is not applicable to window and document objects; for these, use .width()
try
How can I get the browser's scrollbar sizes?
From Alexandre Gomes Blog
function getScrollBarWidth () {
var inner = document.createElement('p');
inner.style.width = "100%";
inner.style.height = "200px";
var outer = document.createElement('div');
outer.style.position = "absolute";
outer.style.top = "0px";
outer.style.left = "0px";
outer.style.visibility = "hidden";
outer.style.width = "200px";
outer.style.height = "150px";
outer.style.overflow = "hidden";
outer.appendChild (inner);
document.body.appendChild (outer);
var w1 = inner.offsetWidth;
outer.style.overflow = 'scroll';
var w2 = inner.offsetWidth;
if (w1 == w2) w2 = outer.clientWidth;
document.body.removeChild (outer);
return (w1 - w2);
};
in your code
if(jQuery(window).width()-getScrollBarWidth(); <= 720){
// a code to make arrows in the carousel stop working
}
A bit outdated thread, but i've found this solution
function getWidth(){
return ((window.innerWidth > 0) ? window.innerWidth : screen.width);
}
If you are using Bootstrap > 3 then I will suggest you something.
Bootstrap ships with .container class in its Css and predefined. And its altering with #media queries.So my working code sample for this is below.
function detectWidth(){
var width = $('.container').eq(0).outerWidth() ;
console.log(width);
if(width<750){
// do something for XS element
}else if(width>=750 && width<970){
// do something for SM element
}else if(width>=970 && width<1170){
// do something for MD element
}else{
// do something for LG element
}
}
I realize this is an old thread, but I think it can still benefit from this answer.
var width = window.outerWidth;
This will give you the width of the window including scrollbars, which is what media queries use, I believe.

How to listen for layout changes on a specific HTML element?

What are some techniques for listening for layout changes in modern browsers? window.resize won't work because it only fires when the entire window is resized, not when content changes cause reflow.
Specifically, I'd like to know when:
An element's available width changes.
The total height consumed by the in-flow children of an element changes.
There are no native events to hook into for this. You need to set a timer and poll this element's dimensions in your own code.
Here's the basic version. It polls every 100ms. I'm not sure how you want to check the children's height. This assumes they'll just make their wrapper taller.
var origHeight = 0;
var origWidth = 0;
var timer1;
function testSize() {
var $target = $('#target')
if(origHeight==0) {
origWidth = $target.outerWidth();
origHeight = $target.outerHeight();
}
else {
if(origWidth != $target.outerWidth() || origHeight = $target.outerHeight()) {
alert("change");
}
origWidth = $target.outerWidth();
origHeight = $target.outerHeight();
timer1= window.setTimeout(function(){ testSize() }),100)
}
}
New browsers now have ResizeObserver, which fires when the dimensions of an element's content box or border box are changed.
const observer = new ResizeObserver(entries => {
const entry = entries[0];
console.log('contentRect', entry.contentRect);
// do other work here…
});
observer.observe(element);
From a similar question How to know when an DOM element moves or is resized, there is a jQuery plugin from Ben Alman that does just this. This plugin uses the same polling approach outlined in Diodeus's answer.
Example from the plugin page:
// Well, try this on for size!
$("#unicorns").resize(function(e){
// do something when #unicorns element resizes
});

Resizing font based on screen width

Can someone help me with JavaScript code that resizes a font in a div if the screen width is lower than 1100px
if (window.screen.width <= 1100) {
var item = document.getElementById("div1");
item.style.fontSize = "25px";
item.innerHTML = "String";
}
This is what I have so far. Can someone help me with what to do next?
Your code works for me in JS Fiddle. Perhaps you are not specifying the correct id for your div or something like that.
http://jsfiddle.net/trott/GqFPY/
If you are hoping the code will be triggered on a browser resize, you will need to bind it to an event. (See Michael's answer.)
You will need to bind the action to the window.onresize event:
var resizeFonts = function() {
var item = document.getElementById("div1");
if (window.screen.width <= 1100) {
item.style.fontSize = "25px";
item.innerHTML = "String";
}
// Otherwise set a larger font
else item.style.fontSize = "30px";
};
window.onload = resizeFonts;
window.onresize = resizeFonts;
I have an OLD blog in which I posted about changing the font size, but it was made to show how to use jQueryUI slider. Maybe you can use some of the logic there to create your own solution:
http://weblogs.asp.net/thiagosantos/archive/2009/03/21/my-first-time-with-jquery-ui.aspx

Categories