What is the most straightforward method to access these four buttons?

Looking to create 4 interactive buttons with a unique behavior. When clicked, the chosen button will change its background image while the other 3 buttons retain their original background image unless hovered over by the user. Additionally, hovering over any of the buttons should also trigger a change in the background image.

The challenge lies in finding the simplest way to achieve this effect without complex coding. Attempted a solution using :hover in CSS, but encountered issues with missing hover effects.

$s_btn_1.on('click',function() {
        if (chosen!=1){
            chosen = 1; 
            console.log('chosen');
        $.get("services_1.php", function(data){
         // $service_box.html(data);

        }); 

        return_default();

        $folder1.css('background',"url('images/services/btn1_hover.png')");
        $folder1.css('background-size',"100% 100%");

    }

    });

  $s_btn_2.on('click',function() {
        if (chosen!=2){
            chosen = 2;
            console.log('chosen');

            $.get("services_2.php", function(data){
        //      $service_box.html(data);
            });
            return_default();

            $folder2.css('background',"url('images/services/btn2_hover.png')");
            $folder2.css('background-size',"100% 100%");
        }
    });

    $s_btn_3.on('click',function() {
        if (chosen!=3){
            chosen = 3;
            return_default();

            $folder3.css('background',"url('images/services/btn3_hover.png')");
            $folder3.css('background-size',"100% 100%");
        }
    });

    $s_btn_4.on('click',function() {
        if (chosen!=4){
            chosen = 4;
            return_default();

            $folder4.css('background',"url('images/services/btn4_hover.png')");
            $folder4.css('background-size',"100% 100%");
        }
    });
  //$("#service_btn").addClass(".folder1_hover");
    function return_default(){
        $folder1.css('background-image',"url('images/services/btn1.png')");
        $folder2.css('background-image',"url('images/services/btn2.png')");
        $folder3.css('background-image',"url('images/services/btn3.png')");
        $folder4.css('background-image',"url('images/services/btn4.png')");
        $folder1.css('background-size',"100% 100%");
        $folder2.css('background-size',"100% 100%");
        $folder3.css('background-size',"100% 100%");
        $folder4.css('background-size',"100% 100%");
    }
});

Answer №1

After completing my task successfully, I am sharing my code here as I believe it is the most straightforward and easy to understand method.

$(document).ready(function() {   
     var buttons = {
         'bg_o' : ['images/buttons/btn1.png','images/buttons/btn2.png','images/buttons/btn3.png','images/buttons/btn4.png'],
         'bg_h' : ['images/buttons/btn1_hover.png','images/buttons/btn2_hover.png','images/buttons/btn3_hover.png','images/buttons/btn4_hover.png'],
         '$all_btn' : $('.all_buttons'),
         '$folders':[$('#folder-1'),$('#folder-2'),$('#folder-3'),$('#folder-4')],
         'folders_status':new Array('inactive','inactive','inactive','inactive')
         ,jquery_function : function(){
            buttons.$all_btn.each(function(){
                $(this).click(function(){
                    for(i=0;i<4;i++){
                        var image_url_o = new Array();
                        image_url_o[i] = {'background-image':'url('+buttons.bg_o[i]+')'};       
                        buttons.$folders[i].css(image_url_o[i]);    
                        buttons.folders_status[i]='inactive';
                    }
                    for(i=0;i<4;i++){           
                        var parent_element = buttons.$folders[i].parent();                       
                        if($(this).attr('class') == parent_element.attr('class')){
                            var image_url_h = {'background-image':'url('+buttons.bg_h[i]+')'};
                            buttons.$folders[i].css(image_url_h);   
                            buttons.folders_status[i]='active';
                        }   
                    }
                });
                $(this).mouseover(function(){
                    for(i=0;i<4;i++){
                        var image_url_o = new Array();
                        image_url_o[i] = {'background-image':'url('+buttons.bg_o[i]+')'};
                        if(buttons.folders_status[i]=='inactive')
                        buttons.$folders[i].css(image_url_o[i]);    
                    }
                    for(i=0;i<4;i++){           
                        var parent_element = buttons.$folders[i].parent();                       
                        if($(this).attr('class') == parent_element.attr('class')){
                            var image_url_h = {'background-image':'url('+buttons.bg_h[i]+')'};
                            buttons.$folders[i].css(image_url_h);   
                        }   
                    }

                });
            }); 
         }
     }
     buttons.jquery_function();
});  

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

Redirecting to a specified URL after submitting a POST request in Angular

I recently started learning Angular and decided to follow this tutorial on creating a MailChimp submission form. I made sure to customize the list information & id according to my own needs. However, after submitting the form, I encountered an issue wh ...

How can we replicate the 'setTimeout' feature in Node.js without causing any interruption to the event loop?

After extensive research, I have been trying to figure out how to implement non-blocking code in Node.js. However, all the examples I have come across are tied to functions that already have built-in callbacks. Therefore, I attempted to create my own funct ...

Installing Vue JavaScript using the npm command

Embarking on my journey as a Vue JS learner, I took the plunge to install Vue and delve into creating web applications using it. So, I globally added npm Vue. npm install --global vue-cli This action resulted in: npm WARN deprecated [email protected]: T ...

Preventing the selection of 'None selected' upon dropdown change

When using the NameTextBox Dropdown, all names are available for selection. Upon changing a name and clicking on search, the associated details are retrieved. However, by default, 'None Selected' is displayed. Is there a way to prevent 'None ...

What is the best way to apply ngClass to style a JSON object based on its length?

Currently, I am working with a mat-table that displays data from a JSON object. My goal is to filter out all records with an ID of length 5 and then style them using ngClass in my HTML template. How can I achieve this? Below is the code I am working with: ...

Executing PHP script within a Node.js socket server program

I have a JavaScript file running a normal TCP socket using node.js. Before sending a response back to the client, I need to validate the data using some PHP (MySQL) code. Can someone guide me on executing this PHP code inside the JavaScript file? Most of t ...

Opacity is a key feature of Bootstrap 5 background colors

I am currently facing a challenge with creating an OR divider using Bootstrap 5, as it seems to not display correctly when compared to Bootstrap 4. The text's background color also appears to have some transparency in my project. Here is the code I a ...

Find the identifier that does not currently exist in the collection of objects

There is a situation where I have an array and an object that consists of arrays of ids, which are essentially permission objects. My goal now is to extract the ids that do not exist in the given object. Can someone assist me with devising the necessary l ...

Unusual Behavior Uncovered in jQuery Selectors

Have you ever noticed a peculiar behavior of jQuery selectors? I recently discovered that when the page contains elements with non-unique IDs, jQuery returns different results for the same selectors: Here's an example of HTML code: <button id=&ap ...

Retrieve the file path of an uploaded image in a Razor view using jQuery Ajax

I have been facing challenges while working on an ASP.NET MVC3 application where I am developing a custom image gallery. The browser being targeted is IE9, which rules out the option of using HTML5 File API. All my code resides within a strongly typed Razo ...

Navigation bar remaining fixed on mobile devices

I have been working on a bootstrap site at http://soygarota.com/blog/public After checking the code multiple times, I have added the bootstrap.min.css, bootstrap.min.js, and jQuery. However, for some reason, the header navigation is not collapsing when vi ...

TypeScript Generic Functions and Type Literals

Everything seems to be running smoothly: type fun = (uid: string) => string const abc: fun = value => value const efg = (callback:fun, value:string) =>callback(value) console.log(efg(abc, "123")) However, when we try to make it generic, we e ...

At what point in the process does Angular/PrimeNG switch the CSS classes from 'p-' to 'ui-'?

So I've encountered quite a peculiar problem. I've managed to create a customized PrimeNG component that seems to be functioning properly, but there are a couple of issues at hand: Despite using ViewEncapsulation.None, just like with other Pri ...

Trouble handling Ajax response

I have two JSP files described below. The parent JSP page contains a Select dropdown box with two options. Another JSP file, dispTable.jsp, displays select boxes inside a table. If the user selects "one" from the dropdown in the parent.jsp page, I want ...

-=:Heading with a decorative vertical line=:-

Currently, I am working on a CSS project that requires page titles (headings) to be centered with horizontal lines positioned vertically on both sides. Additionally, there is a background image on the page which means the title's background must be tr ...

Develop two varieties of user account models using Mongodb/Mongoose

Currently, I am utilizing mongoose in my nodejs project and I am seeking advice on creating a MongoDB schema that caters to two different user types: employees and clients. Both of these users will be registering through the same page (I am implementing pa ...

I am having trouble selecting Bootstrap radio buttons on my ASP.NET Core MVC application

My asp.net mvc core web application has the following code to display 2 radio buttons:- <div class="form-group"> <label class="control-label" style="font-weight:bold"> ...

Double Looping of Ajax on Shopify Order Form

I have an Ajax order form on a product page. Every time the #submit-table button is clicked, it should display a drop-down menu with updated cart information, such as quantities and prices, along with the newly added products. Here's an example of th ...

Breaking down an object's data in a React component

I need to figure out how to properly extract variables and props from this code snippet: const MyComponent = (props, {data}) => { return ( <div data-set={props["data-set"]}> {data.name} </div> ) }; ...

Internet Explorer 10 not triggering the 'input' event when selecting an option from the datalist

Within this particular scenario, there is an input field paired with a corresponding datalist element. My aim is to develop JavaScript code that actively listens for when a user chooses an item from the list. Most resources suggest utilizing the "input" ev ...