I created some jQuery code that modifies a button when it is hovered over, however, I ended up writing the code individually for each button. What steps can I take to turn it

Is there a way to turn the code for each button on my website into a jQuery function that can be applied to any button?

This is how the code currently appears:

$(document).ready(function() {
    $("#linkXML").hover(
        function() {
            $("#linkXML").css({
                "-webkit-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)",
                "-moz-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)",
                "box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)"
            });
        },
        function() {
            $("#linkXML").css({
                "-webkit-box-shadow": "",
                "-moz-box-shadow": "",
                "box-shadow": ""
            });
        }
    );
});

Currently, I'm copying and pasting this code for every button and just changing the element it's called upon.

I would appreciate it if you could advise me on how to create a single function that can be applied to any element to trigger this behavior.

Answer №1

To achieve this effect, I recommend utilizing CSS rather than relying on JavaScript.

#XMLlink
{
    // add your custom styles here
}

#XMLlink:hover
{
    -webkit-box-shadow: inset 0px 0px 98px -34px rgba(51,173,255,0.79);
    -moz-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79);
    box-shadow: inset 0px 0px 98px -34px rgba(51,173,255,0.79);
}

If you intend to apply this style to multiple elements, consider creating a separate class for it.

Answer №2

Have you considered targeting the button element in your jQuery selector?

$(document).ready(function() {
    $("button").hover(
        function() {
            $(this).css({
                "-webkit-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)",
                "-moz-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)",
                "box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)"
            });
        },
        function() {
            $(this).css({
                "-webkit-box-shadow": "",
                "-moz-box-shadow": "",
                "box-shadow": ""
            });
        }
    );
});

Answer №3

To ensure that all buttons are selected, assign them the same class name.

$(document).ready(function() {
    $(".linkXML").hover(
        function() {
            $(".linkXML").css({
                "-webkit-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)",
                "-moz-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)",
                "box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)"
            });
        },
        function() {
            $(".linkXML").css({
                "-webkit-box-shadow": "",
                "-moz-box-shadow": "",
                "box-shadow": ""
            });
        }
   );
});

Answer №4

Consider using a CSS class instead.

$(document).ready(function() {
  $(".linkXML").hover(
    function() {
      $(this).css({
        "-webkit-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)",
        "-moz-box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)",
        "box-shadow": "inset 0px 0px 98px -34px rgba(51,173,255,0.79)"
      });
    },
    function() {
      $(this).css({
        "-webkit-box-shadow": "initial",
        "-moz-box-shadow": "initial",
        "box-shadow": "initial"
      });
    }
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="linkXML">Button</button>
<button class="linkXML">Button</button>
<button class="linkXML">Button</button>


Suggested Approach:

If possible, utilize CSS by adding a class and applying styles to the buttons there.

.linkXML:hover {
  -webkit-box-shadow: inset 0px 0px 98px -34px rgba(51, 173, 255, 0.79);
  -moz-box-shadow: inset 0px 0px 98px -34px rgba(51, 173, 255, 0.79);
  box-shadow: inset 0px 0px 98px -34px rgba(51, 173, 255, 0.79);
}
<button class="linkXML">Button</button>
<button class="linkXML">Button</button>
<button class="linkXML">Button</button>


In case your links are linked to an .xml file via the href attribute, you can opt for a substring matching attribute selector:

a[href$=".xml"] {
  -webkit-box-shadow: inset 0px 0px 98px -34px rgba(51, 173, 255, 0.79);
  -moz-box-shadow: inset 0px 0px 98px -34px rgba(51, 173, 255, 0.79);
  box-shadow: inset 0px 0px 98px -34px rgba(51, 173, 255, 0.79);
}
<a href="example.xml">Link</a>
<a href="example.xml">Link</a>
<a href="example.xml">Link</a>

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

I have my server running on port 6666. I am able to receive a response from Postman, however, when I attempt to access localhost:6666 in my browser, it displays a message

[image description for first image][1] [image description for second image][2] [image description for third image][3] There are three images displayed, indicating that the server is operational and responding with "hello" in Postman, but there seems to ...

Comparing AJAX to a source script request

As I was exploring the Google API today, I came across their sample code where they simply request a URL using: <script src="src="https://www.googleapis.com/customsearch/v1?key=AIzaSyCVAXiUzRYsML1Pv6RwSG1.."></script> Before seeing this, I ha ...

Triangle Top Megamenu Design

Currently, I am implementing a navbar in bootstrap v4.4.1 that includes a mega menu dropdown feature. In my design, I want to include a triangle at the top of the dropdown menu. While I have managed to add the triangle successfully, I am facing difficulti ...

What is the best way to eliminate data from a channel title using jQuery?

$(function() { $(".track").draggable({ containment:"document", appendTo:document.body, connectToSortable:"#playlist tbody", revert: true, revertDuration: 0, cursor: "move", helper: "clone", ...

Is there a way to automatically execute this function when the React component is loaded, without the need for a button click?

After spending a few days trying to figure this out, I'm hitting a wall. This ReactJS project is new for me as I usually work with C#. The goal is to create a print label component that triggers the print dialog when a link in the menu is clicked. Cu ...

Progress bar carousel component based on advancement movements

Here is the mockup I am working with: https://i.sstatic.net/bIepQ.png So far, I have made good progress with this code: https://codesandbox.io/s/codepen-with-react-forked-16t6rv?file=/src/components/TrendingNFTs.js However, I am facing a couple of challe ...

The console.log for a GET request in Express Router is displaying undefined parameters

After searching extensively on SO for a question similar to mine, I have come to the realization that my issue should be quite straightforward. The closest thread I discovered was this link. My current focus is on learning Node.JS, and I am in the process ...

Creating a unique Angular JS / Material / Datatables application - Proper script loading sequence required based on page context

My top two declarations placed above the closing body tag. When used in a material dropdown page, the current order of these scripts works fine. However, when I switch to my datatables page (which is a separate page), I need to swap the order of the two s ...

The JQuery app dynamically adds a new input row each time the current input row is filled, repeating this process N

I am looking to dynamically add rows to a table with 3 input fields each. After filling out all the inputs in one row, I want to append a new row with identical input fields. <table> <thead> <tr> <th>H</th> ...

Is the express.json() middleware for parsing JSON request body designed to handle synchronous calls?

According to Express.js's documentation, it is recommended to avoid using synchronous functions as much as possible. This is because in high-traffic websites, the accumulation of synchronous calls can negatively impact the performance of the applicati ...

Iterating over the local storage to locate a specific item

Utilizing local storage extensively has been beneficial for maintaining state by storing the session on the client side. However, a challenge arises when updating the session. Within my code, there are multiple lists of objects that I serialize in JSON fo ...

Animating toasts in Bootstrap

Exploring the options available at https://getbootstrap.com/docs/4.3/components/toasts/ To customize your toasts, you can pass options via data attributes or JavaScript. Simply append the option name to data- when using data attributes. If you're lo ...

Storing a component in browser storage using JavaScript and Angular

I am currently working on developing an Angular application that allows users to "favorite" a business card and store it in local memory. I am facing challenges with actually storing the clicked element in the browser's local memory. Furthermore, I f ...

Unfortunately, I am unable to utilize historical redirection in React

When an axios request is successfully completed, I want to redirect. However, I am encountering an error that looks like this: https://i.sstatic.net/irTju.png Below is the code snippet: import React, { useState, Fragment } from "react"; import S ...

Generating URL parameters for Ajax requests on the fly

My current project involves creating a dynamic form where the number of fields displayed changes based on the user's selection from a dropdown menu. This means that depending on what option they choose, anywhere from 2 to 20 different fields may be sh ...

Identifying CSS on iPhone and iPad: A Guide

I need to adjust the CSS style based on different devices. This is how I currently have it set up: <link rel="stylesheet" type="text/css" href="@Url.Content("~/Content/Destop.css")" media="only screen and (min-width: 1224px)"/> <link rel="s ...

Tips for getting a plugin to function properly when the page is refreshed in Nuxt app

I am currently incorporating the vue GAPI plugin into my project. While it functions smoothly when navigating between pages, I encounter an error upon refreshing: vue-gapi.common.js?15fd:241 Uncaught (in promise) Error: gapi not initialized at GoogleAuth ...

Transferring items between different containers without using innerHTML

I've got an embedded <ul> within a (hidden) <aside id="idDetails">. How can I move the ul element from inside the aside and position it in a <div id="projectSide"> without using innerHTML? Any solutions in both plain JavaScript and j ...

Creating dynamically generated routes in Angular or Angular 9 before initialization

I'm currently working on a project where I am in the process of converting an AngularJS application to Angular. The main challenge that I am facing at the moment revolves around routing. To sum it up: My requirement is to define routes based on an AP ...

Printing pages with Bootstrap without disrupting cards

My goal is to print a basic bootstrap page using window.print(). Here is what the page looks like (with multiple div.col-md-12 & cards) : <div class="overview"> <!-- Takes up entire screen width --> <div class="row"> <div ...