What other technique can I use to replace the creation of a jquery division?

I`m relatively new to all things related to web technologies and I am currently practicing and learning about them.

On my practice page, I've experimented with various elements, including changing div heights based on the viewport height. Here's an example:

<script>
<!--
 document.write('<div class=\"head\" id=\"head\" style=\"height:'+viewportheight/6+'px\">');
//-->
</script>
</div>

I realize that this code is not ideal, but it gets the job done. However, I've encountered issues with using the .css method in jQuery. Even after including the jQuery library, the following code doesn't seem to work:

$( 'body' ).css( {
    'width'   : viewportwidth + 'px',
    'height'  : viewportheight + 'px'
} );

I have confirmed that the variables for height and width contain valid values by outputting them using document.write(). I have also tried using constant values but to no avail.

Could you please provide guidance on how to create divs with dynamic values without needing a script tag each time, or how to properly utilize the .css method in this context?

Thank you and happy holidays!

Answer №1

My new practice page features various elements designed to adjust the height of a div based on the viewport height.

Why resort to jQuery or Javascript for this task? You can easily achieve this with CSS alone:

@media screen and (max-width: 995px) , screen and (max-height: 700px) {
 /* add styles here
 ...
*/
}

In the realm of Web development, all HTML styling can be accomplished using jQuery or JavaScript, as well as CSS. However, utilizing them for basic styling or viewport adjustments can be excessive, akin to using a missile instead of a gun to achieve your goal.

Further reading available here:

EDIT: (for width)

To gain insight into the functionality of media queries, refer to this example on JSFiddle

@media screen and (max-width: 1500px) {
    body {
        background: grey;
        border-top: 2px solid #DDDDDD;
    }
}
@media screen and (max-width: 800px) {
    body {
        background: red;
        border-top: 2px solid #DDDDDD;
    }
}
@media screen and (max-width: 400px) {
    body {
        background: black;
        border-top: 2px solid #DDDDDD;
    }
}

Adjust the browser viewport width to observe the color changes of the body...similarly, you can apply different styles to various div elements.

EDIT (for height)

View the demonstration here

html, body {
    /* apply universal styling */
    background-color: grey;
    height: 100%;
    width: 100%;
    margin: 0;
    padding: 0;
}
@media (max-height: 600px) {
    body {
        background-color: red;
    }
    @media (max-height: 400px) {
        body {
            background-color: yellow;
        }
        @media (max-height: 200px) {
            body {
                background-color: black;
            }
        }

Answer №2

What do you think of this solution?

Javascript:

This code snippet targets an element with the id mydiv and adjusts its height to 500 pixels.

document.getElementById('mydiv').style.height="500px";

HTML:

 <div id="mydiv">My div!!</div>

Check out the demonstration on this JSFiddle link

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

I'm experiencing an issue with res.redirect() as it is not directing me to the expected page. Despite no errors being shown, I am left wondering what

Despite everything working as expected, I am facing an issue with redirecting the user to a different URL after they send a message. I have tried using res.redirect from the server side in response to an AJAX POST request, but it seems like I am still on t ...

Exploring the different routing options for Nuxt.js: Dynamic versus Basic Routing

Can anyone suggest the best way to set up routing in Next.js for only Home, Gallery, and Contact us? Should I use dynamic routing or just keep it basic? Any ideas on how to path them? I'm still learning, so I would appreciate some guidance. I've ...

Django: Error - < found where unexpected

Using a combination of Django and jQuery, I have implemented a file upload feature with AJAX. Everything seems to be working correctly - the files are successfully uploaded, reflected in the database, and stored on the server. However, upon completion of t ...

The onSubmit event handler seems to be malfunctioning within a Reactjs form

I recently started using React and encountered an issue with my form: class CustomForm extends React.Component { handleFormSubmit = (e) => { e.preventDefault(); const title = e.target.elements.title.value; const content = e ...

What steps can be taken to prevent a wrapper's CSS from affecting its enclosed elements?

My container div includes some opacity and auto height that I don't want to affect all elements within it. Is there a way to preserve the container's styles without impacting its contents? ...

Error: The callback specified is not a valid function

Here is a function example: reportAdminActions.reportMemberList(project, function(data) { console.log(data); }); This particular function gets called by another ajax operation, similar to the one shown below: reportMemberList: function(projectId, ca ...

Iterate over the MVC model and deliver the results

Below is the code snippet for the model that retrieves names and ids... public class AccountType { public int Id { get; set; } public string Name { get; set; } public static AccountType[] AvailableAccountTypes { get { ...

Display the date that is 3 days after the selected date from the Date Picker in the text field

This is the date picker code I am currently using: var d = new Date(); $(function () { $("#datepicker").datepicker({ minDate: d, dateFormat: 'mm-dd-yy' }); }); I want to enhance this functionality so that when a date is ...

Tips on incorporating Prisma model into prisma-offset-pagination

I am currently implementing pagination using the prisma-offset-pagination package. To do this, I need to utilize Prisma Model in my code, but I'm unsure of the correct approach: Refer to line: 02 const result = prismaOffsetPagination({ model: user ...

Combining switch statements from various classes

Is there a way to merge switch statements from two different classes, both with the same function name, into one without manually overriding the function or copying and pasting code? Class A: protected casesHandler(): void { switch (case){ ...

After receiving the response, the Ajax success function does not run as expected

I have written the following code: $(".simpleCart_shelfItem button").click(function() { $(this).prop('disabled', true); $(this).addClass('disabled'); $(this).html("Adding &nbsp;&nbsp;<i cl ...

Inquiring about design layout for an iPhone application incorporating CSS, jQuery, and JQTouch

I am currently in the process of learning how to develop an iOS website by utilizing Johnathan Stark's book, Building iPhone Apps from O'Reilly. To better understand my issue, please take a look at the desktop version on www.saudialberta.com. Upo ...

The cursor seems to be playing a game of hopscotch every time I

In the text box, I've implemented a feature to prevent typing of a forbidden character: #. While this feature is successful in restricting the input of the forbidden character, there's an issue that arises when data is already filled in the text ...

Is it possible to adjust the height of the dropdown menu in a mat-select component in Angular 7?

How can I adjust the height of a mat-select in Angular7 to display all items properly? Here is my component file: import { Component, ViewEncapsulation } from "@angular/core"; import { FormControl } from "@angular/forms"; /** @title Select with multiple ...

Is there a way to remove specific mesh elements from a scene in Unity?

When I create multiple mesh objects with the same name, I encounter difficulties in selecting and removing them all from the scene. Despite attempting to traverse the function, I have not been successful in addressing the issue. event.preventDefault(); ...

Exploring the power of colors in Tailwind CSS and Material UI for your CSS/SCSS styling

Discovering unique color palettes like the Tailwind Color for Tailwind CSS and theMaterial UI colors has been inspiring. These collections offer a range of beautifully named colors from 100 to 900 and A100 to A400, reminiscent of font styles. I am intrig ...

Using Unobtrusive Ajax, learn to integrate data-ajax-confirm with sweetalert

Here is an example of a form using AJAX: <form method="post" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-confirm="Are you sure you want ...

Steps to Utilize Google Apps Script from a Website

I've been on a mission to find the solution to my problem. I have a basic web page with HTML/CSS/JS. What I want is for users to visit the page and immediately have it call up a Google script I created, which will pull information from a spreadsheet a ...

Uploading base64 arrays from AngularJS to a Node.js server: Allowing Access-Control-Origin

My current challenge involves sending an array of base64 strings from my Client Side (AngularJs) to my NodeJs Server. However, I've encountered a peculiar situation. When I attempt to send an object containing the base64 data along with other properti ...

Vue.js - Trouble with Rendering Elements

I'm facing an issue with displaying data fetched from an API using axios in Vue.js. Despite writing the code, the elements are not being rendered and don't appear in the elements console. See below for the code snippets: <div class=" ...