Modifying a section of the source name using jQuery continues to occur repeatedly when the window is resized

I have written a piece of code that is designed to identify the src attribute of all images within a specific div and modify the src name when the window width is less than 900 pixels. The code works perfectly when the page is refreshed, but I encounter an error when I resize the window:

GET file://macintosh%20hd/Users/jessicamele/Desktop/tom%20mendicino/images/boys3_small_small_small_small.jpg net::ERR_FILE_NOT_FOUND

The issue seems to be that the "_small" suffix keeps getting appended repeatedly. Below is the snippet of code responsible for this behavior:

<div class="threePicsBoys group">
   <img src="images/boys3.jpg" alt="street signs" class="boysPics1">
   <img src="images/boys2.jpg" alt="city house" class="boysPics2">
   <img src="images/boys1.jpg" alt="2 boys" class="boysPics1">
   <img src="images/boys4.jpg" alt="philly signs" class="boysPics2">
   <img src="images/boys5.jpg" alt="religious statue" class="boysPics1">
</div>

$(function() {
    if (windowWidth <= 900) {
        var img = $(".threePicsBoys.group").find("img").map(function() { 
            var src = $(this).attr("src");
            var newName = src.replace(".jpg","_small.jpg"); 
            $(this).attr("src",newName);
        });
    }
});
}

I am seeking assistance to resolve this issue.

Answer №1

This code snippet is designed to detect if the browser window is narrow enough to require changing the image src, and will revert back once the window width exceeds 900 pixels. I made some modifications to ensure proper functionality. The variable windowWidth was not declared, and other parts of the script appeared unnecessary.

var narrowWindow = false;
$(window).on('load resize', function(){
    if($(window).width() <= 900){
        if(!narrowWindow){
            $('.threePicsBoys.group img').each(function(){
                var src = $(this).attr("src");
                var newSrc = src.replace(".jpg","_small.jpg");
                $(this).attr("src", newSrc);
            })
            narrowWindow = true
        }
    }else{
        if(narrowWindow){
            $('.threePicsBoys.group img').each(function(){
                var src = $(this).attr("src");
                var newSrc = src.replace("_small.jpg",".jpg");
                $(this).attr("src", newSrc);
            })
            narrowWindow = false
        }
    }
})

I hope these revisions are helpful for you

Answer №2

If the window width is less than 900, this code will continue to run indefinitely. To ensure that it only runs when the window width changes, you need to include the appropriate event binding.

$(window).resize(function() {
    if (windowWidth <= 900)
    {
        var img = $(".threePicsBoys.group").find("img")
        var src = img.attr("src");
        if (!(src.indexOf("_small.jpg") > -1))
        {
            var newName = src.replace(".jpg","_small.jpg");
            img.attr("src",newName); 
        }
    }
});

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

Troubleshooting Variable Issues in PHP and JavaScript

On my PHP page, I have a while loop where I am retrieving the following... print $divLeft.strip_tags($row->twitterUser)."?size=normal\"/><br \/>".$row->twitterUser.$divRight."<a href='javascript:void(0);' id=&apos ...

enhancing angular directives with data binding while replacing HTML content inside the compile function

I am currently attempting to develop a directive that will substitute an input field with a custom-made input field. Unfortunately, I am encountering challenges with getting the data binding to function properly, as the model does not display in the direct ...

Google Maps integrated AWS server

While utilizing an AWS server for my application, I have encountered a difficulty with Google Maps. When running my application using localhost, Google Maps functions perfectly fine. However, when attempting to run the application using an IP address, it f ...

Mastering the art of invoking a JavaScript function from a GridView Selected Index Changed event

In my current setup where I have a User Control within an Aspx Page and using Master Page, there's a GridView in the User Control. My goal is to trigger a javascript function when the "Select" linkbutton on the Gridview is clicked. Initially, I succe ...

Tips on retrieving and sending an XML string in PHP to JavaScript using MySQL

Here is the code snippet I have: <input type='button' value='clickme' onclick='download(\"\" . $rowtable['Protocolo'] . \".xml\", \"\" . $rowtable['XML&a ...

Having difficulty generating dynamic rows and tree dropdowns in AngularJS

Struggling to implement dynamic row functionality with Angular JS. The rows are working well, but I also need to incorporate a tree dropdown within each row. Unfortunately, clicking the "add row" button populates the same data in all rows. I have shared m ...

When utilizing the File System Access API, the createWritable() method functions perfectly within the console environment but encounters issues when executed

I've been diving into the File System Access API for an upcoming project and I'm struggling with using the createWritable() method. Specifically, I'm encountering issues with this line of code: const writable = await fileHandle.createWritab ...

Soft keyboard on mobile fails to update when arrows are used in Ajax-populated dropdown menus

I am working on a web form that includes two select fields: Country and City: <select id="country" onchange="getCity(this);"> <option value="">-- Please select your country --</option> <option value="1">Austria& ...

Utilizing Backward and Forward Navigation with AJAX, JavaScript, and Window.History

TARGET Implement Ajax for fetching pages Utilize JavaScript to update the window URL Leverage Window History to preserve Ajax page for seamless forward-backward navigation without reloading the page Modify the Navigation bar's attributes (such as co ...

CSS not being applied to Next.js HTML pages

Currently, I am utilizing Nextjs and including the flaticon css in _app.js as follows: import '../public/assets/css/flaticon.css'; In the upcoming section, an error is being encountered: @font-face { font-family: 'Flaticon'; src: ...

Is it a bad idea to incorporate JavaScript functions into AngularJS directives?

I came across this snippet of code while working with ng-repeat: <div ng-show="parameter == 'MyTESTtext'">{{parameter}}</div> Here, parameter represents a string variable in the $scope... I started exploring if it was possible to c ...

Change the color of specific elements in an SVG using React

Can I change the dynamic primary color from ReactJS to a specific class in an SVG file? If yes, how can it be done? Error.svg <!-- Generator: Adobe Illustrator 26.0.0, SVG Export Plug-In . SVG Version: 6.00 Build 0) --> <svg version="1.1&qu ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...

iPhone 6 (iOS) users may face compatibility issues with iframe and fancy box features

I am currently learning how to use jQuery and the fancybox library. In my Angular 1 and Ionic project, I have successfully implemented fancybox with an iframe. Everything works perfectly on browsers and Android devices, but on iOS, a loader icon appears an ...

What is the best way to create stylish corners on my website?

I'm struggling with creating a corner like the one shown in the image. As a beginner in frontend development, I attempted to write the following code but now I'm stuck. The Snippet: * { margin: 0; padding: 0; } body { height: 100vh; ...

Adding an element to the second-to-last position in a list

In the context of a HTML unordered list <ul id = "master_key_list"> <li id="master_key_23" class="available_element">Fix the Peanut Butter</li> <li id="master_key_24" class="available_element">Focus on Price Sensitivity</li& ...

Replace Jade script with block override

Having trouble overriding a Jade script. tag, nothing seems to work. Here is the code snippet: Layout.jade block foot footer.container#footer .row .twelve.columns All rights reserved. &copy; 2015 Pet Feeder block scripts ...

Height and Width Dilemma in Visuals

Can you help with changing image resolution using jQuery? I have a background image applied to the body using CSS/PHP. My goal is to make the image fill the entire window by applying the screen height and width, without using repeat style. The code I am c ...

Auto play feature malfunctioning in Onsen-UI Carousel attribute settings

When utilizing onsen UI in my mobile web application, I encountered an issue with the autoplay property not functioning properly within the carousel. <ons-page> <ons-toolbar> <div class="left"> <ons-toolbar-button on ...

Using jQuery, wrap two specific HTML elements together

I am working with a set of elements: <div id="one">ONE</div> <div id="two">TWO</div> <div id="three">THREE</div> <div id="four">FOUR</div> <div id="five">FIVE</div> My goal is to wrap a DIV tag ...