Using Jquery to dynamically adjust the size of a div based on the width and height of the browser window

How can I dynamically change the height of a .test div based on the browser width and height? I want the value to update whenever the browser is resized.

$(document).ready(
  function() { 

    window.onresize = function(event) {
      resizeDiv();
    }

    function resizeDiv() {
      var vpw=window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
      var vph=window.innerHeight || document.documentElement.clientHeight ||document.body.clientHeight;
      $('.test').css({'height': vph + 'px'});
    }
               
);
.test
{
  background: green;
  padding: 20px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="test"></div>

Answer №1

Illustration

demo

javascript

function adjustSize() {
    $(".sample").css({
    width:  $(window).width(),
    height: $(window).height()
});
}
adjustSize();
$(window).resize(function(){
 adjustSize();
});

To reduce by a certain number of pixels

function adjustSize() {
    $(".sample").css({
        width:  $(window).width() - 15,
        height: $(window).height() - 15
    });
 }

Answer №2

There is an Uncaught SyntaxError: Unexpected token ILLEGAL

The issue lies in your use of ‘ and ’ instead of '. Make sure to use ' or " for your script to run correctly.

Answer №3

To optimize your layout, it is recommended to employ responsive design techniques. Check out this resource for more information:

Here's an example of how you can implement responsive design in your code:

@media only screen and (min-width: 1300px) { #divId {width:1000px;}}

@media screen and (max-width: 860px) {#divId {width:800px;} }

@media screen and (max-width: 650px) { #divId {width:600px;}}

@media screen and (max-width: 480px) { #divId {width:400px;}}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

IE6 disrupts stored layouts

I've encountered a strange issue with my design in IE6. It loads perfectly at first, but after reloading it a couple of times, everything suddenly collapses. The strange part is that when I upload an updated version, it fixes the issue, only to break ...

Ways to extract input values from a specific row in a textbox as users input data

On a button click, I am dynamically adding data to an HTML table using the loadbooks function. When the user clicks on the button, the table is populated with data. <button id="button" onclick="loadbooks()"></button> function loadbooks() { ... ...

What is the best way to align a scalable SVG image in the center?

My goal is to horizontally align this SVG within its container, which could be any div, body, or other element. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1250 190" preserveAspectRatio="xMidYMid slice" class="svg-content"> &l ...

Instructions for adding a name to a string based on certain conditions

I am attempting to prepend a company name to a card number using the code provided. The challenge I am facing is incorporating the specific rules for each company as conditions for an if statement. Although I acknowledge that my current approach with the ...

Having trouble locating the nivoslider IE8 jQuery bug, can't seem to track it

I am encountering an issue with the nivoslider script in IE8 and I am having trouble identifying what is causing it. The nivoslider works perfectly fine in all other browsers except for IE8. Any help or guidance on this matter would be greatly appreciated ...

unable to transform this string into an object

https://i.sstatic.net/O46IL.pngWhy am I encountering difficulties converting this string into an object? Any assistance on resolving this error would be greatly appreciated. onSignup(data:any){ localStorage.setItem('users',JSON.string ...

Center two elements within a div container both horizontally and vertically

I am trying to vertically center a text and a button within a container. The text should be positioned in the middle of the div, while the button should be aligned to the right. What is the best way to achieve this layout where the text element is centere ...

What is the process of integrating Bootstrap into a Node project?

I recently set up a MEAN stack project using npm and am currently including Bootstrap via CDN: link(rel='stylesheet', href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css') However, I want to add Bootstrap using ...

The execution of jQuery was hindered due to the implementation of PHP include

Having an issue with jQuery not working in index.php when including the file header.php. The nav sidebar is included, but clicking the chevron does not trigger anything. It only works when I directly include header_user.php without checking the UserType in ...

Exploring the power of AngularJS in manipulating Google Maps polygons with the help of ng-repeat

I recently started using a Google Maps plugin specifically designed for AngularJS, which can be found at . My goal is to display polygons on the map, so my HTML code looks something like this: <google-map center="map.center" zoom="map.zoom" draggab ...

An image inside this stylishly framed photo with rounded corners

.a { clip-path: polygon(10% 0, 100% 0%, 100% 100%, 10% 100%,10% 60%, 0% 50%, 10% 40%); } .a { position: relative; width: 500px; height: 500px; background:url("https://cdn.pixabay.com/photo/2020/02/16/07/55/thailand-4852830_960_720.jpg"); border-radi ...

Reposition the navbar-brand

I need to adjust the position of my navbar-brand slightly to the right as it is currently overlapping with another button. How can I achieve this in my HTML code? Here's a snippet: <nav class="navbar navbar-expand-lg navbar-light bg-light"> ...

JavaScript: Obtaining a Distinct Identifier for Various Replicated Entries

Imagine we have an object: var db = [ {Id: "201" , Player: "Jon",price: "3.99", loc: "NJ" }, {Id: "202", Player: "Sam",price: "4.22", loc: "PA" }, {Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" }, {Id: "204", Player: ...

Enhancing the camera functionality of the HTML <input> tag for iPhone and Android devices

I am currently working on a mobile web application that requires access to the device's camera. I am aware that this can be achieved using the following code: <input type="file" accept="image/*" capture="camera" /> The code snippet above suc ...

Tips for activating the default 500 error page in Next.js

I'm having trouble getting Next.js to display its default 500 error page. While most sources discuss creating a custom error page, the Next.js documentation only briefly references their built-in 500 error page. I want the default page to show up when ...

duplicate styling for individual table cells

I am in need of a span element inside a td tag that I am generating within a table. In order to ensure the span fills the td, I have set it as an inline-block with a width and height of 100%. However, when pressing the delete key in the last cell, it star ...

Difficulty with Ajax post function in CodeIgniter

I am currently working with CodeIgniter version 3.1. When attempting to use Ajax post, I encountered a 403 (Forbidden) error in the console. [POST http://localhost/test/post 403 (Forbidden)] HTML <div class="post"> <input type ...

Having trouble sending a request in next.js with Docker during the build process?

When utilizing the getStaticProps function to send a request to my backend API from another Docker container, I am encountering an issue. Despite ensuring that the API URL is accurate, the static page fails to be created. This is due to the requirement for ...

The navbar background spans the full width of the screen, with all content contained within minimum and maximum width parameters

Currently, I am working on a fluid website design where I have set specific min-width and max-width values. However, I want the navigation bar background to extend across the entire screen width without being limited by the max width parameter, while still ...

Error message appearing when attempting to add a product to the cart in Magento using AJAX

Encountering an error with the magento 1.8 ajax cart, stating "product not found" The javascript code I implemented: function setLocationAjax(url,id){ var data = jQuery('#product_addtocart_form').serialize(); data += '& ...