How do I check if the width of the image is > 80% and if it is, set width to 80% in JavaScript?

My HTML is this:

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Aerocello</title>
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="stylesheet.css">
<body>
    <div class="gallery" *ngFor="let image of images; let i = index;">
        <img src="logo2.png" alt="logo" class="centre">
        <script>
            // if (what goes here?) {
                // and here
            // }
        </script>
    </div>
    <div class="idk">
        <p class="roboto">hi</p>
    </div>
</body>
</html>

and my CSS is this:

body {
    background-color: #AEAEAE;
    margin: 0;
    padding: 0;
    
    height: 100vh;
}

.gallery {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    position: relative;
    height: 100%;
}

.centre {
    width: auto;
    max-width: auto;
    height: 80%;
    max-height: 80%;
    display: block;
    margin-left: auto;
    margin-right: auto;
    
   overflow: auto;
   margin: auto;
   position: absolute;
   top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

.roboto {
    font-family: roboto;
}

So, My image’s height is 80% and the width is set proportional to that but I want to check if width is over 80% and if it is set it to 80% and set the height to be proportional to the new width. How do I do that in JavaScript?

I didn’t try anything really, I didn’t know where to start?

New contributor

Cosmac is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

<script>
    window.onload = () => {
        const images = document.querySelectorAll(".gallery img");

        images.forEach(image => {
            image.onload = () => {
                const parentWidth = image.parentElement.clientWidth;
                const imageWidth = image.naturalWidth;
                const imageHeight = image.naturalHeight;

                if (imageWidth > 0.8 * parentWidth) {
                    image.style.width = "80%";
                    image.style.height = "auto";
                } else {
                    image.style.height = "80%";
                    image.style.width = "auto";
                }
            };
        });
    };
</script>

New contributor

Raj is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

1

To achieve the functionality where you want to check if the image’s width exceeds 80% of the parent’s width and adjust it accordingly using JavaScript, you can integrate the logic within the <script> block in your HTML file.

Here’s the full solution based on your provided code:

HTML with JavaScript:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Aerocello</title>
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <link rel="stylesheet" href="stylesheet.css">
</head>
<body>
    <div class="gallery">
        <img src="logo2.png" alt="logo" class="centre">
        <script>
            // Select the image element
            const img = document.querySelector('.centre');

            // Get the parent container (gallery div)
            const parent = img.parentElement;

            // Function to check and adjust image width
            function adjustImageWidth() {
                // Get the parent width and image width
                const parentWidth = parent.offsetWidth;
                const imgWidth = img.offsetWidth;

                // If image width is greater than 80% of the parent's width, adjust it
                if (imgWidth > parentWidth * 0.8) {
                    img.style.width = '80%';
                } else {
                    img.style.width = 'auto'; // Reset to the original width if it's within the limit
                }
            }

            // Call the function initially to adjust on load
            adjustImageWidth();

            // Optionally, add a resize event listener to handle changes in window size
            window.addEventListener('resize', adjustImageWidth);
        </script>
    </div>
    <div class="idk">
        <p class="roboto">hi</p>
    </div>
</body>
</html>

Explanation:

  1. Selecting the image and parent element:

    • const img = document.querySelector('.centre'); selects the image element with the class .centre.
    • const parent = img.parentElement; gets the parent container of the image (the .gallery div).
  2. Function to check and adjust the image width:

    • The adjustImageWidth() function compares the width of the image (imgWidth) with 80% of the parent container’s width (parentWidth * 0.8).
    • If the image width exceeds 80% of the parent container, it adjusts the image width to 80% (img.style.width = '80%').
    • If the image is smaller than 80%, it resets the width back to its natural width (img.style.width = 'auto').
  3. Initial adjustment and dynamic resizing:

    • The function adjustImageWidth() is called once the page is loaded to check and adjust the image width accordingly.
    • An event listener is added to the resize event to ensure the image adjusts properly if the window size changes.

Your CSS:

You can leave your CSS unchanged, but you may want to update your .centre class a bit, as it’s using max-width: auto, which isn’t valid. You can just remove max-width: auto and ensure the image behaves as intended.

Updated CSS for .centre:

.centre {
    width: auto;
    max-width: 100%; /* Ensure the image doesn't stretch beyond its container */
    height: 80%;
    max-height: 80%;
    display: block;
    margin-left: auto;
    margin-right: auto;
    overflow: auto;
    margin: auto;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
}

This solution checks the image’s width against 80% of its parent’s width and adjusts it accordingly, both on page load and when resizing the window.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật