What could be causing the issue with setting the right margin (element.style.marginRight = xxx) not working?

I used JavaScript to set the margin-right of a div when the window is resized.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script>
    function adjustMargin(){
        let cardElement = document.querySelector(".maincard");
        var width = cardElement.offsetWidth;
        let circleElement = document.querySelector(".card_circle");
        var marginRightValue = (400 - width) / 10;
        circleElement.style.marginRight = marginRightValue +"px";
        document.querySelector(".abc").innerHTML = circleElement.style.marginRight;
        
    }
    window.onresize = adjustMargin;

</script>

</head>
<body>
    <div class="col">
            <a class="maincard" href="IALA boyage.html">
                <div class="card transition">
                    <h2 class="transition">IALA Buoyage</h2>
                    <div class="card_circle transition"></div>
                </div>
            </a>
        </div><div class="col">
            <a class="maincard" href="IALA boyage.html">
                <div class="card transition">
                    <h2 class="transition">IALA Buoyage</h2>
                    <div class="card_circle transition"></div>
                </div>
            </a>
        </div><div class="col">
            <a class="maincard" href="IALA boyage.html">
                <div class="card transition">
                    <h2 id="abc" class="transition abc">IALA Buoyage</h2>
                    <div class="card_circle transition"></div>
                </div>
            </a>
        </div
</body>
</html>

The 'marginRight' function is successful as innerHTML changes while resizing. However, the margin-right is not visually changing, and I am unsure of the reason

I previously placed the script just before the '' tag, which resulted in a browser error 'marginFunction' not defined.

The CSS code:

.transition {
        transition: .3s cubic-bezier(.3, 0, 0, 1.3);
    }
    
    /* Other CSS styles... */
    
    .maincard{padding: 10px;}

If the provided code snippets do not work, you can view the full webpage on Codepen.

Answer №1

There appears to be an error in your JavaScript code related to calculating the margin-left (ml) value. Instead of subtracting the value from 400, it should be subtracted from the width of the card container. Moreover, the CSS defines a fixed width of 450px for the card_circle element, which could impact this calculation.

<script>
    function adjustMargin() {
        let card = document.querySelector(".maincard");
        let containerWidth = card.offsetWidth;
        let circle = document.querySelector(".card_circle");
        let ml = (card.offsetWidth - containerWidth) / 10; // Correction made here
        circle.style.marginRight = ml + "px";
        document.querySelector(".abc").innerHTML = circle.style.marginRight;
    }
    window.onresize = adjustMargin;
    window.onload = adjustMargin; // Call the function on page load
</script>

I added window.onload = adjustMargin; to ensure the margin adjustment function runs when the page is first loaded. This guarantees the correct margin is applied from the beginning.

Answer №2

After making a small adjustment, I was puzzled as to why it wasn't functioning correctly before. The updated code snippet is producing the desired outcome, although it now only modifies the marginLeft of the initial element rather than all of them. I suspect it may be due to data types or querySelector(s), and I intend to investigate further.

<script>
function marginFunction() {
    let cardd = document.querySelector(".maincard");
    let w = cardd.offsetWidth;
    let circle = document.querySelector(".card_circle");
    let ml = (450 - w) / 2; // Corrected calculation
    circle.style.marginLeft = "-" + ml + "px";
    document.querySelector(".abc").innerHTML = circle.style.marginLeft;
}
window.onresize = marginFunction;
window.onload = marginFunction; // Trigger on initial load

APPLYING TO ALL ELEMENTS WITH SAME CLASS

<script>
    function marginFunction() {
        let cardd = document.querySelector(".maincard");
        let w = cardd.offsetWidth;
        let circle = document.querySelector(".card_circle");
        let ml = (450 - w) / 2; // calculates margin required as per width of card
        
        //for creating new style rule so that all the cards are affected
        var sheet = document.createElement('style')
        sheet.innerHTML = ".card_circle {margin-left: -" + ml + "px}";
        document.body.appendChild(sheet)
    }
    window.onresize = marginFunction;
    window.onload = marginFunction; 
</script>

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

Position a div at the center of the page while aligning it inline with another div

Is there a way to center an element on the screen while having another element positioned to its left? I have tried using float left and adjusting the padding of the center element to match the width of the left element. However, this method may not work ...

Responsive Text and Alignment in the Latest Bootstrap 5

My goal is to center my div element while keeping the text aligned to the left. Here's the code I have: <div class="container"> <div class="row"> <div class="col"> <h1>< ...

Sorting items using jQuery filter

I am working with two sortable div containers that are connected using connectWith. Both containers contain draggable items that can be moved as desired. These items have specific classes such as group1 and group2. Let's refer to the containers as con ...

"What is the process for creating a single line border around a pandas DataFrame using df.to_html method

After exporting a pandas dataframe as an HTML table to Outlook, I noticed that the double cell borders are not aesthetically pleasing. I am seeking assistance in changing them to a single line border. Please refer to the attached screenshot and code snip ...

Angula 5 presents a glitch in its functionality where the on click events fail

I have successfully replicated a screenshot in HTML/CSS. You can view the screenshot here: https://i.stack.imgur.com/9ay9W.jpg To demonstrate the functionality of the screenshot, I created a fiddle. In this fiddle, clicking on the "items waiting" text wil ...

Executing code on the server-side (back-end) using Javascript: A step-by-step guide

Imagine wanting to execute JavaScript on the server side instead of exposing the code to the client. For example: Starting with the JS native window Object from the browser. Performing all JavaScript processing in the backend by passing the window Object ...

Tips for applying a CSS wrapper to an element, not just text

I am working with a group of span elements within a td that has a set width. My goal is to wrap the span elements onto new lines without breaking up the text inside them. For example, if I have: <td> <span>bind</span> <span&g ...

The array used within the useEffect hook and the getCoordinates function appears to be distinct when printed with console

Utilizing GoogleMap API for Custom Location Display I have an imported array of JSON objects named data which includes an address property. The Google Maps API is used to retrieve coordinates from the addresses in order to generate custom markers displaye ...

Unable to retrieve data from the JSON file after making a $http.post call

Currently facing an issue with my grocery list item app developed in AngularJS. I have simulated a connection to a server via AJAX requests made to local JSON files. One of the files returns a fake server status like this: [{ "status": 1 }] I am att ...

The value of useEffect does not change even after it is defined in ReactJS

I am working on a component where I need to fetch data from an API after it has been rendered, and store the response in a useState value. However, when attempting to set the state using the useEffect callback after fetching the API, nothing seems to be w ...

What issues are present with the JavaScript event management in this scenario? (Specifically using the click() and hover() jQuery functions)

Currently, I am in the process of developing a proof-of-concept for a project that mimics Firebug's inspector tool. For more detailed information, please refer to this linked question. You can view an example page of my work which has only been teste ...

Can two div elements be positioned next to each other without relying on CSS float?

Every time I try to use CSS float to align two elements next to each other on a webpage, IE and Firefox always throw unexpected surprises my way. Is there an alternative method to position two divs side by side on a website without relying on CSS float? ...

Having trouble extracting data from a particular cell within an HTML table using jQuery

I am struggling to extract row data from a table for utilization in a modal. Provided below is my code for Views. <link rel="stylesheet" type="text/css" href="//cdn.datatables.net/1.10.10/css/jquery.dataTables.min.css"> <link href="@Url.Content(" ...

Creating a hyperlink within an @Html.LabelFor tag

In my current asp.net mvc project, I have a code snippet that generates a name like this - @Html.LabelFor(x => x.ReturnAirTemperature, new { style = "position: absolute;top: 310px;left: 18px;z-index: 10000;font-weight:bold" }) Here is the model associ ...

Calculating values within the TR using jQuery: A step-by-step guide

I have a situation where I am looking to use jQuery to calculate values within a table row. Below is a screenshot of the page where I need to determine the number of working days for an employee and display the count as NWD (Number of Working Days). http ...

Utilize the power of Javascript/AJAX or jQuery to submit multiple forms simultaneously

I am currently working on a project which involves having 3 forms on a single page. The reason behind this is that one of the forms is displayed in a modal dialog. My goal is to allow users to submit all 3 forms with a single button click, and I also wan ...

Position the center of an Angular Material icon in the center

Seeking help to perfectly center an Angular Material icon inside a rectangular shape. Take a look at the image provided for reference. https://i.sstatic.net/oFf7Q.png The current positioning appears centered, but upon closer inspection, it seems slightly ...

How to add values at a particular index within an array using JavaScript

First, I start by creating an array with a specific size. $("#bntSize").one('click', function(e){ var memory = $("#memory").val(); console.log(memory) html = ""; for(var i = 0; i < memory ; i++){ ...

Using the Strikethrough Feature in React

Is it possible to apply a strikethrough effect to a checkbox's label text when toggled on and off? In my system development process, I've utilized various methods. What modifications should be made in the fComplete method for this feature to wor ...

Guide on printing in an Ionic application using print.js without the need to open the printer setup page

Our team is currently working on an Ionic web application that utilizes printer functionality. To enable printing, we have integrated the Print.js npm package. However, when we initiate the print method, a setup page displaying details such as printer na ...