Activate jquery code during interaction

I am in need of a scalable image that can be centered within a scalable <div>. Currently, I have a wrapper <div> along with the scalable <div> that contains the image. Additionally, there is some jQuery code in place to calculate the width of the <body> and determine the available space for the <div>/<img />. The website content spans 745px, leaving the rest of the window for the div and image placement. Here's what I currently have:

<div class="ad_banner_holder" id="ad_banner_holder" style="width: 100%;">
    <div class="ad_banner" id="ad_banner" style="background: white; text-align: center; position: absolute;">
        <a href="http://www.finconsult.ro/" target="_blank"><img id="the_ad" style="position: fixed; max-width: 800px; margin-top: 82px;" src="http://ww1.particularul.ro/images/ads/3rdtry2.jpg" /></a>
    </div>
</div>

<script type="text/javascript">
    $(window).load(function () {
        var adwidth = $("body").width();
        adwidth = adwidth - 760;
        $("#the_ad").css("width", adwidth);
        $("#ad_banner").css("width", adwidth);
    });
    $(window).resize(function () {
        var adwidth = $("body").width();
        adwidth = adwidth - 760;
        $("#ad_banner").css("width", adwidth);

    });
    $(window).resize(function () {
        var adwidth = $("#ad_banner").width();
        $("#the_ad").css("width", adwidth);

    });
</script>

The issue arises when refreshing the page as the browser centers the image initially but then resizes it from the current point towards the right, causing it to deviate from the center. It's perplexing why this behavior occurs only under specific triggers.

Furthermore, attempting to change the trigger for image resizing to .hover() produces the same result: the centered image widens and shifts away from its central position.

Any assistance or explanation on this matter would be greatly appreciated.

Answer №1

A more efficient way to handle resizing in jQuery is to use the standard document ready function to detect when the page has loaded.

$(function() {
    var adwidth = $("body").width();
    adwidth = adwidth - 760;
    $("#the_ad").css("width", adwidth);
    $("#ad_banner").css("width", adwidth);

    //combine the two resize handlers

    $(window).resize(function() {
        var adwidth = $("body").width();
        adwidth = adwidth - 760;
        $("#ad_banner").css("width", adwidth);

    });
    $(window).resize(function() {
        var adwidth = $("#ad_banner").width();
        $("#the_ad").css("width", adwidth);

    });

});

Answer №2

You have the power to combine everything:

<script type="text/javascript">
    $(document).ready(function(){
        var screenWidth; // accessible within this function

        // a optimized resize function
        function adjustWidth(){ 
            screenWidth = $("body").width() - 760;
            $("#the_ad").css("width", screenWidth);
            $("#ad_banner").css("width", screenWidth);
        }

        // triggered on DOM ready and window resize event
        adjustWidth();
        $(window).on('resize', function(){
            adjustWidth();
        });
</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

The images on my website are not displaying properly on different devices

My attempt at creating a website for fun and testing purposes is facing issues when viewed on mobile devices. The images and specially positioned elements are not displaying correctly, extending beyond the page boundaries. I have tried adding the viewport ...

Having trouble with my CSS hover not functioning properly

I need some help with my code. Can you please take a look and let me know why the hover effect is not working? Thank you! <style> #moreDiscussHome:hover{ background-color: #ffffff; } </style> <a id="moreDiscussHome" style="co ...

I am looking to integrate a WordPress blog post into my Bootstrap website

Is there a way to showcase the 3 most recent posts from my WordPress blog (www.xyz.wordpress.com) on my Bootstrap HTML website without using PHP? Feedburner got me close, but I'm limited in CSS styles and don't want the "Headline by Feedburner" ...

Finding elements through their text representation

I am struggling to select an element using the text "SELECT PRODUCT" in the following HTML: <div style="font-family: franklin-gothic-urw; font-weight: 400; font-style: normal; font-size: 19px; opacity: 1; color: rgb(255, 255, 255);">SELECT&nbsp; ...

Forming a space between borders

I'm attempting to create a space within a div's border that can accommodate an image, much like so: Is there a method to achieve this using only CSS? The only solution I have found is: .box { background: url(img.png) bottom left; border ...

Select only eBook files using this HTML form: {file-type}

I am looking to implement a form that includes an option to upload files by selecting "choose file". However, I want to restrict the displayed files to only show .epub and .mobi files when the user opens the selection pop-up box on their operating system. ...

Browser crashing due to drag-and-drop upload of desktop images

I've set up a form for uploading images using ajaxForm. I added a feature where users can drag and drop photos from their desktop (HTML5 drag & drop). Everything works smoothly when the photo is small, around 2mb. However, an issue arises when attempt ...

Changing the dimensions of a div according to the container's size

I'm currently working on a project that involves an HTML video player with custom Javascript controls, utilizing SVG graphics for the backgrounds. However, I've encountered an issue with using the css calc() function to resize the divs based on t ...

What safety measures should be implemented when granting users permission to modify HTML and CSS on your site?

I'm really impressed by the customization options on Tumblr. Users can edit the HTML and CSS of their profiles, which is something I'd love to incorporate into my own site. However, I'm concerned about the security implications of allowing t ...

The CSS border on a div has inexplicably ceased functioning in Chrome, yet continues to work perfectly in

Just a moment ago, something strange happened while I was working on my memory game. After reopening the page, the borders around the divs stopped showing up when navigating with the keyboard arrows. (Click in the window to activate the arrow keys.) Normal ...

Create a grid or flex layout with Bootstrap 4 that features a sticky first row and column

Does anyone have any suggestions on how to make the attached grid/table layout responsive using Bootstrap 4's flex/grid system? The layout should include a sticky first row and column for navigation items. I attempted using w- & h- classes, but it do ...

How to use AJAX to retrieve the text content of an HTML option value?

I have a script that displays a list of values, which I want to write: <option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}" In addition, I have the function setSelectedName in my .j ...

When the mouse hovers over, include a fade-in effect for the image

I am working with two overlapping images and have successfully implemented a function to display the second image on mouse hover. However, I am struggling to incorporate a CSS transition property for a smoother image transition effect. Currently, when the ...

By harnessing a JSON response

After sending an ajax request, the server's response is as follows: {"error":false,"success":true} The ajax code used: $.ajax({ url: '/update', type: 'post', data: $(this).serialize(), success: function(response) ...

Send information to the server using AJAX

Greetings everyone! I am currently in the process of developing a mobile version for a website and I have a query regarding a specific task. In the scenario described below, the code extracts information from data attributes of a button and displays it in ...

Tips for creating a Bootstrap table with a "table-bordered" style, fixed header, and scrollable body

How can I keep the table header fixed while allowing the body to scroll without breaking the table layout? I've tried using the CSS below, but it results in the width of the header columns being different from the width of the body columns. Any sugges ...

What methods can be employed to maintain a consistent width for a multi-line span that aligns with the content?

Inside a div, I have 2 spans. When the content of the first span is short enough to fit on one line, the span's width matches the text content and positions the second span next to it. If the content of the first span is long and causes it to wrap, t ...

What is causing my HTML wrapper to malfunction?

Below is the HTML code for my website: <div id="wrapper"> <div id="header"> <img src="images/MyBannerFinished.jpg" alt="Header" width="803" class="headerimage" /> </div> <!--- End Header ---> <div id="navbar"> <ul ...

Rearranging anchor tag order with the power of JQuery

Imagine I have five anchor tags <a id = "A" class = "Home">Home</a> <a id = "B" class = "Maps">Maps</a> <a id = "C" class = "Plans">Plans</a> <a id = "D" class = "Community">Community</a> <a id = "E" clas ...

Adding margin padding to a Material UI Navbar: Step-by-step guide

Hey there, I've added buttons to my Navbar from Mui. However, I'm running into an issue where the margin and padding won't change no matter what I do. I'm trying to create some space between them. Please see the code below: import { use ...