Setting the width of a <div> when resizing the window - javascript

So I got this application in Vuejs that is divided with css grid into 3 divs basically: a sidebar, a configpanel and a preview. I would like to set the width of the preview div in the px unit according to the current screen size and when the screen gets resized
For clarification, I made a gif of a website that does pretty much EXACTLY what I want: https://gyazo.com/d667756474e7f4fa18e2d5d64a0dee5a
As you can see in the gif, every time the screen gets resized, the particular <div> gets assigned a new class for some reason (no idea why or how) and the div's width automatically gets updated with a new px value.
At first I thought I could do something like this in the created() hook:
window.addEventListener("resize", () => {
let preview = window.document.querySelector(".preview");
preview.style.width = `${preview.offsetWidth}px`;
});
But that doesn't work.
I got a really simple sample project set up in a codesandbox here.
Ideally, I would like to know how to dynamically set the width in pixels like the website does in the gif.
Additionally, just out of curiosity, I would like to know why and how that particular website generates a new class every time the screen gets resized (I've seen it a couple of times now and I wonder what it is).

If I have known what you mean correctly, your solution can be the code below (Add code below to your CSS file and add every class you want to it):
#media screen and (max-width: 750px) {
.selector {
some code here...
}
}
The code above will apply the styles defined to elements selected when the width of the device screen is 750 pixels or less.

Related

Navigation bar doesn't work with Intersection Observer API

I have a problem when I use the Intersection Observer API. I am trying to use it for, once the nav-bar is not visible anymore when you scroll, make this latter appears with a white background and fixed to the viewport.
I first of all tried to console.log('visible') and console.log('visible') when the nav-bar is visible or not and I succeed ! But when I wanted to apply the new class when the navbar wasn't visible anymore, my page starting to get mad : the class was applied and removed, and the console was only displaying "visible", "not visible" all the time very frequently.
I think it is because when I apply the class, it moves the rootMargin (of the options object) but I don't know how to fix it.
My entire website (my code is in app.js) : https://replit.com/#Xeway/IntersectionObserver#app.js
PS : I only have build app.js, HTML and CSS are codes made by FreeCodeCamp.
PS : Sorry for the link, but I can't share this code here because my code uses backtick and it doesn't seems to work ^^ Also, try to open the website with a big width because it's responsive and you can see more precisely the problem when it's on a computer's screen width.
Thank you in advance for your answers guys :)
Intersection observer is not needed for your case.
You just need to apply class to your header, when window is scrolled beyond certain height.
In your case, it would be equal to the height of the header.
So, when the window scroll height > height of the header, then apply class
and in the else, remove the class.
Call the same function on document.ready as well (To check the window scroll position on the page load, if the window is already scrolled).
Here is the little script for your help:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
// assume 100px is the height of the header
if (scroll >= 100) {
addScrolledClassToHeader();
} else {
removeScrolledClassToHeader();
}
});
function addScrolledClassToHeader() {
$('header.site-header').addClass('header-is-scrolled');
}
function removeScrolledClassToHeader() {
$('header.site-header').removeClass('header-is-scrolled');
}

Imitate 1920x1080 window in a smaller div with sizing of elements

I am working on a project that uses two windows, similar to a video board, where the main screen is a control panel of sorts with a "preview" screen, and the secondary screen is a projection of the viewing content in 1920x1080 resolution. I would like the smaller control panel preview div to match the stylings of the larger viewing window. Currently, I am passing in a "windowInstance" prop to my styled component and adjusting the styles that way, for example:
const SomeComponent = styled.div`
height: ${props => props.windowInstance === 'controlPanel' ? '300px' : '400px'};
`
// ...
return (
<SomeComponent windowInstance={windowInstance} />
)
(windowInstance is passed from the parent component. this is not relevant for the problem at hand, and it gets a bit complicated)
Obviously, this has gotten quite tedious as my app has grown, and nothing is quite right unless I meticulously calculate the difference in window sizes as a percentage and translate that to the new property values. What I want to know is if there is any way with CSS or JS that I can unify these styles and have the results render correctly and identically on both screens.
Important to note is that neither window needs to be responsive or will ever be resized. Here is a sketch I did in excalidraw to better describe the goal:
I was able to solve my problem using the css property zoom - which I was previously unaware of. It works like a charm. My preview screen happens to be exactly 47.5% of the size of my viewing window. So I solved the problem like this:
// Wrapper.js
return (
<StyledWrapper className={windowInstance === 'controlPanel' && 'preview-screen'}>
{children}
</StyledWrapper>
)
// index.css
.preview-screen {
zoom: 47.5%;
}

Text does not resize on screen resize

I'm using the text-only carousel seen here:
jsFiddle
Here is my resize code:
window.addEventListener("resize", resetCarousel);
function resetCarousel(){
setCarouselHeight('#carousel-text');
$('#carousel-text').carousel({
interval: 15000
});
The problem is that when the screen resizes the div enclosing all the text items does not resize accordingly (i.e. it's not responsive). The setCarouselHeight function is used to determine the largest height required for all text items to display. I need the setCarouselHeight to be fired every time the screen resizes. When I do it manually (i,e, window.onresize=func), even after using a timeout, the item sizes reflect the ones used in the old position, not the resized position. Any insight would be greatly appreciated.
After two days of toying with this and coming oh so close, I tried the Owl carousel and got what I needed right away. In the end it is much simpler than bootstrap's. The key is to use the AutoHeight example and turn autoheight to false. It automatically sizes the div to the tallest text piece you have and is very responsive. http://owlgraphic.com/owlcarousel/index.html. Hope this helps someone.
I think no need to use js or owl plugin for responsive the slider. It's can be done by simple css query. My css is below:
.carousel-inner>.item{
min-height:350px;
}
#media screen and (max-width:767px){
.carousel-inner>.item{
min-height:250px;
}
}
#media screen and (max-width:569px){
.carousel-inner>.item{
min-height:200px;
}
}
Check my live demo on jsfiddle

Positioning div elements left & top not working with content in FireFox

I've got a webpage with a full-screen canvas. Over the canvas I'm going to place and position divs that will contain UI elements for the canvas. I'm using jQuery to create the divs and give them the css style they need. I also re-position and/or re-size them in JavaScript upon window re-size. The problem is, as soon as I enter even one space into a div, FireFox says 'NO!' and seems to ignore any css changes made by JavaScript, even if I remove the content of the div again.
Here's some technical details:
The div I'll show is a fullscreen div that overlays the canvas and functions as dim-screen in case there are dialogs the user has opened so the canvas appears darker and extra attention is pulled towards the dialog.
The css I'm using is:
.ui_layer {
position: absolute;
top:0px;
left:0px;
}
#ui_layer_dim {
background-color: #000000;
opacity: 0.5;
}
In JavaScript I have my own function that creates the div, but it runs this jQuery:
$("<div id='ui_layer_dim' class='ui_layer' style='z-index:1'/>");
Then, on onWindowResize (tiggered by a window 'resize' eventlistener), I change the div's width and height to fit the new window size:
gameUI.layers["ui_layer_dim"].onWindowResize = function() {
this.css("width", window.innerWidth + "px");
this.css("height", window.innerHeight + "px");
};
In Chrome this works perfectly, even if I place content in the div. FireFox works, but only when the div is in it's initial state. One change to the div's contents and 'BOOM it goes': No more dynamic sizing.
I've tried the different css position settings, tried setting the width and height attributes using the css function, using the style function of the element and using setAttribute to see if it's caused by some sort of incompatibility; the results didn't change.
I've run a series of tests to see what happens to the html as soon as content is placed into the div and noticed something weird: The inspector and css rules won't show changes to the width and height of the window's innerWidth and innerHeight. Neither does the div itself, but I've set up some logging to view info about the window's innerWidth and innerHeight before setting the div's width and height and some logging about the div's width and height after setting it, and that actually shows the correct dimensions...
After building and testing the system for several days I have no clue anymore what could cause the problem. Like I've said before: Chrome works as it should so I know my code technically works, but it might just be that a different approach is needed to make it work in FireFox. I hope anyone knows. Help would be greatly appreciated!
Edit: Here's a fiddle with the code, try running in FireFox, resize the result, it should resize the grey div as well. Now, right click the result, go to the inspector and put some text or even a space inside the div and resize again. Not working for me. Link: http://jsfiddle.net/UsLL6/
Edit 2: Here's a screenshot that will hopefully clear up the problem I'm having. Marked yellow is the initial state of the browser width, I set it to very narrow to be able to show the problem more clearly. Marked orange is the state after I made the browser wider a bit. You can see the grey div doesn't resize with it as it should, neither do the inspector value and the CSS rules value, but the console shows the correct value. The first ("Setting property:.....") was retrieved from window.innerWidth, the second ("Property height now has....") was retrieved from the actual width property from the div element using style.getPropertyValue.
Just noticed IE gives the same result as FireFox, but yea..IE....
Is your gameUI.layers known by mozilla?
Did you try the jQuery solution?
$(window).resize(function(){
$('#ui_layer_dim').width(window.innerWidth);
$('#ui_layer_dim').height(window.innerHeight);
});
When adding and removing content from the div using JavaScript it works. Even though the problem does not exist for me anymore I'm still very confused by the fact that editing the div in the FF inspector creates such a weird result.

Problem adjusting scrollbar after images have been loaded on page

Problem description: I got a page with a table containing text and thumbnails. Usually the table contains more entries than would fit on the screen leading to a scrollbar on the right side. No Problem so far. When loading the page or choosing the next page of the table (pagination) the table gets rendered - the scrollbar is at the bottom of the page where i would like it to be after complete load. Then the thumbnails are getting shown. Due to the fact that they are a bit bigger in size than the text in the table the table gets bigger in heigth leading to the scrollbar being set somewhere in the middle of the page.
Page and table after the images have been loaded, as you can see the scrollbar is somewhere in the middle (vertical) of the page:
I do not want to fiddle around with the thumbnail size. Customers are used to the actual design and image/icon sizes.
Usign the pagination function the table is the only element that gets replaced ont he page. "onload" on tables does not work unfortunatly.
What can i do to have the scrollbar appear after the images have been loaded (leading to the correct placement of the scrollbar)?
Is there a way to set the scrollbar to the bottom of the page after the table has been fully loaded?
There are jQuery plugins to wait for all images to be loaded, but I couldn't get them working on the quick, maybe you can: here and here.
However, you also could use the following hack: watch for the table height and if it changes, scroll to the bottom:
var lastHeight;
function watchTable(){
var currentHeight = $('#myTable').height();
if(currentHeight !== lastHeight){
lastHeight = currentHeight;
$('#myDiv').scrollTop(currentHeight);
}
}
setInterval(watchTable, 100);
see my demo fiddle for a working example.
The best practice is to set the widths of thumbnails in HTML or CSS, if all the thumbnails are of the same size, you can just add the style like
.thumbnail {
width: 150px;
height: 100px;
}
Or, if they size can vary, you must add width and height attributes to the ` tag.
Another solution is to:
Look at the document's scrolltop on DOMload, and look if it's at the bottom, then on onload event (which would be fired when all the images loaded) check again and if scroll to the desired position if needed.
But I recommend always set the dimensions for images, so the page wouldn't jump when they are loaded.
Edit: If you're loading images dynamically, you can do two things:
Preload images and then insert them with the right dimensions.
Use onload for images, however, you still would need to use the document.createElement('img'), so you could be sure that all the images are loaded.
Anyway, in these cases you should use something like that for each image:
var image = document.createElement('img');
image.onload = function () {
// Image is loaded
};
image.src = 'test.jpg';
Note, that you must set .src after attaching the event, or there could be some problems in Opera.

Categories

Resources