Enhance Your Javascript and jQuery Coding Efficiency

On the website I am currently working on, there are multiple images that enlarge when hovered over. Each item has a unique class to indicate which image should expand upon hovering. I am looking to simplify this process by creating a single function that can be applied to all items individually. This would eliminate the need for extra classes and reduce the size of the JavaScript file. For example, when hovering over a specific column, the picture inside that column will enlarge.

Javscript Code:

$('.webDesignServices').hover(function() {
    $(".webDesignPicture").addClass('transition');
}, function() {
    $(".webDesignPicture").removeClass('transition');
});

$('.graphicDesignServices').hover(function() {
    $(".graphicDesignPicture").addClass('transition');
}, function() {
    $(".graphicDesignPicture").removeClass('transition');
});

CSS Code:

.webDesignPicture {
-webkit-transition: all .4s ease-in-out;
-moz-transition: all .4s ease-in-out;
-o-transition: all .4s ease-in-out;
-ms-transition: all .4s ease-in-out;
}

.graphicDesignPicture {
    -webkit-transition: all .4s ease-in-out;
    -moz-transition: all .4s ease-in-out;
    -o-transition: all .4s ease-in-out;
}
.transition {
    -webkit-transform: scale(1.5); 
    -moz-transform: scale(1.5);
    -o-transform: scale(1.5);
    transform: scale(1.5);
}

HTML code (2 have been excluded to make it more clear)

<div class = "container-fluid services">
    <div class = "row">
        <div class = "col-md-3 webDesignServices">
            <img class = "img-responsive displayed servicePicture webDesignPicture" src = "img/globe.png" alt = "webdesign" style = "height: 100px">
            <h2 class = "serviceTitles"> Web Design </h2>
            <p class = "serviceDescription"> Cardiff's Premier Web Design. Full Web Solutions For Any Sized Business.</p>
            <button class = "serviceButton displayed" id = "web-design" data-id="#web-design-slide"> Find Out More!</button>
            <div id = "paddingSpace"></div>
        </div>
        <div class = "col-md-3 graphicDesignServices">
            <img class = "img-responsive displayed servicePicture graphicDesignPicture" src = "img/pencil.png" alt = "graphicdesign" style = "height: 100px">
            <h2 class = "serviceTitles"> Graphic Design </h2>
            <p class = "serviceDescription"> Anything From Flyers And Business Cards All The Way To Product Design.</p>
            <button class = "serviceButton displayed" id = "graphic-design" data-id="#graphic-design-slide"> Find Out More!</button>
            <div id = "paddingSpace"></div>
        </div>                                    
    </div>
</div>

Answer №1

Make sure to assign the class enlargeable to all of them for easy identification.

With this in place, you can now execute the following jQuery code:

$(".enlargeable").hover(function() {
  $(this).toggleClass("transition");
});

$(".enlargeable").hover(function() {
  $(this).toggleClass("transition");
});
.transition {
  -webkit-transform: scale(1.5);
  -moz-transform: scale(1.5);
  -o-transform: scale(1.5);
  transform: scale(1.5);
}
.enlargeable {
    -webkit-transition: all .4s ease-in-out;
    -moz-transition: all .4s ease-in-out;
    -o-transition: all .4s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid services">
  <div class="row">
    <div class="col-md-3 webDesignServices">
      <img class="img-responsive displayed servicePicture webDesignPicture enlargeable" src="img/globe.png" alt="webdesign" style="height: 100px">
      <h2 class="serviceTitles"> Web Design </h2>
      <p class="serviceDescription">Cardiff's Premier Web Design. Full Web Solutions For Any Sized Business.</p>
      <button class="serviceButton displayed" id="web-design" data-id="#web-design-slide">Find Out More!</button>
      <div id="paddingSpace"></div>
    </div>
    <div class="col-md-3 graphicDesignServices">
      <img class="img-responsive displayed servicePicture graphicDesignPicture enlargeable" src="img/pencil.png" alt="graphicdesign" style="height: 100px">
      <h2 class="serviceTitles"> Graphic Design </h2>
      <p class="serviceDescription">Anything From Flyers And Business Cards All The Way To Product Design.</p>
      <button class="serviceButton displayed" id="graphic-design" data-id="#graphic-design-slide">Find Out More!</button>
      <div id="paddingSpace"></div>
    </div>
  </div>
</div>

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

Having Trouble Using Fetch API with ASP.NET Core 2 Controllers that Require Authorization

I have the following code on the client side: fetch("/music/index", { headers: { "Content-Type": "application/json" } }) .then(response => { if (!response.ok) { throw response; } return response.json(); }) ...

Issue encountered in TypeScript: Property 'counter' is not found in the specified type '{}'.ts

Hey there, I'm currently facing an issue while trying to convert a working JavaScript example to TypeScript (tsx). The error message I keep encountering is: Property 'counter' does not exist on type '{}'.ts at several locations wh ...

What steps should I take to ensure that clicking this button triggers the API request and returns the data in JSON format?

I'm attempting to have the button with id 'testp' return an api request in json format, however it seems to not be functioning properly. You can find the HTML code link here: https://github.com/atullu1234/REST-API-Developer-1/blob/main/js-bu ...

Innovative way to design a menu using HTML, CSS, and JavaScript that dynamically resizes to a specific width

I'm currently working on a website and I'm trying to create a menu with specific width of 700px. However, I'm unsure whether to tackle this using CSS, JavaScript, or a combination of both. Which approach would be the most straightforward for ...

Styling jQuery Datatables Buttons with CSS Alignment

Currently, I am actively involved in developing a Sharepoint web part that leverages JQuery datatables to format specific reporting results. Here is an overview of how the report appears: https://i.sstatic.net/jXaiN.png An issue has arisen concerning the ...

Looking to find a way to identify strings with hyphens in JavaScript?

I am trying to extract specific parts of a URL that follow a certain pattern like the one below: http://example.com/somepath/this-is-composed-of-hypens-3144/someotherpath Specifically, I am interested in extracting the portion of the URL that consists of ...

Ways to invoke the parent function from a child component in JavaScript

Is there a way to execute a parent function within the Child class while preserving the current context (this) of the Child? I attempted using Parent.testFunc.call(this);, but it resulted in an error (Cannot read property 'call' of undefined). ...

Tips for saving data in the $localStorage as an object

I need to store all the items in $localStorage like this: $localStorage.userData.currentUser = data.name; $localStorage.userData.devId= data.id; $localStorage.userData.userRole = data.roles[0].name; $localStorage.userData.userId = data.user_id; Here is t ...

CSS ID selectors are not functioning properly

In my React.JS project, I am working with a div that contains a button and a list. The list is specifically identified by the id "results". return <div> <Button label="Combine Cards" disabled={!this.props.combineReady} onClick={this.handleCli ...

Disable the parent CSS styling when focusing on the child button

Within an anchor tag, I have a div element. The CSS on the :active state is set to transform the element, but I want to avoid this behavior when focusing on the child element bx--overflow-menu. I am working with NextJS using styled-jsx and SaSS. Here is my ...

Invalid action has been dispatched by the effect:

In my project, I am using Angular 7.1.4. This is an excerpt from my effect code: @Injectable() export class LoginEffects { constructor(private actions$: Actions, p ...

Tips for extracting information from a URL and processing it on a webpage

Looking to pull data from a website using AngularJS. My main project is to create a "shipping cart" page. The resource provided is a URL leading to a webpage with information on a specific product. I need to extract this data and integrate it into my pag ...

Is there a similar function to -moz-linear-gradient in Chrome?

My button's CSS includes background: -moz-linear-gradient(center top, #59a1d8, #27247D) repeat scroll 0 0 #0f78c7;, which works well in Mozilla Firefox. However, it does not display properly in the Chrome browser. Can someone suggest an equivalent cod ...

Extracting data from a JSON object using Angular

Recently, I've been delving into the world of AngularJS and encountered a hurdle with LocalStorage. After spending numerous hours trying to figure out how to save data locally, I believe I have finally got it working as intended. Now, my next challeng ...

What could be the reason that the height: auto property is not creating a content area big enough to accommodate my content

When a user is not logged in, the header displays a logo and a login form that requires ample space. Once the user logs in, the full navigation menu appears in a smaller header size. To achieve this, adjusting the height:auto property of the "site-header" ...

What is the best way to deliver HTML and JavaScript content using Node.js from virtual memory?

Situation I'm currently developing an in-browser HTML/JS editor, utilizing memory-fs (virtual memory) with Webpack and webpack-html-plugin to package the files created by users in the editor. Storing the files in virtual memory helps avoid I/O operat ...

Best method for developing a jQuery plugin

I've been working on developing my own jquery module, but I want to make sure I'm heading in the right direction before things get too complicated. Although it's not shown in this demo, the main goal is to retrieve content via ajax, so the ...

Encountering an 'object object' error message while trying to insert data into a database on WordPress

Currently, I am in the process of developing a website where I need to manage user data by inserting and retrieving it from a database. Despite successfully fetching the data using a custom template, I encountered an issue while trying to insert new data, ...

Tips for generating a selection of option tags from a JSON file using ReactJS

I am currently exploring ReactJS and experimenting with forms. My current project involves creating a list of <option> tags based on the data stored in a local JSON file. After debugging the code, I can confirm that the values are being correctly re ...

Seeking assistance with Shopify - Enhancing User Experience with Javascript Cookies

Is there a way to adjust the settings of how long Shopify stores cookies on your computer for? Currently, it retains cart information for two weeks. Any suggestions on how to modify this? I am considering two possibilities: 1) Making shopping members-only ...