Enhancing Images with Dynamic Captions Using JQuery

I have created a code to add image captions to different div blocks, and it works as intended. However, I am looking for ways to optimize the code and make it shorter. If you have any advice on how to improve it, please let me know!

Thank you in advance.

HTML

<div id="firstBlock" class="block"><p class="caption c1">Description</p></div>
    <div id="secondBlock" class="block"><p class="caption c2">Description</p></div>
    <div id="thirdBlock" class="block"><p class="caption c3">Description</p></div>
    <div id="fourthBlock" class="block"><p class="caption c4">Description</p></div>
    

JQuery


        function animateCaption(captionClass){
            $(captionClass).hover(
                function(){
                    $(this).animate({"margin-left": "0px"});
                },
                function(){
                    $(this).animate({"margin-left": "-200px"});
                }
            );
        }

        animateCaption(".caption.c1");
        animateCaption(".caption.c2");
        animateCaption(".caption.c3");
        animateCaption(".caption.c4");
    

CSS

.caption{
        height: 150px;
        width: 200px;
        text-align: center;
        margin-left: -200px;
        margin-top: 350px;
        background: black;
        color: white;
    }
    

Answer №1

If you want to improve the readability of your JavaScript code, consider the following example:

$('.block').hover(function() {
  $(this).find('.caption').animate({
     "margin-left": "0px"       
  });
}, function() {
  $(this).find('.caption').animate({
     "margin-left": "-200px",
  });
});

Answer №2

Avoid the hassle of creating multiple classes. Simply use a universal class and locate the caption element within.

$(".block").hover(
    function () {
        $(this).find(".caption").animate({
            "margin-left": "0px"
        });
    },
    function () {
        $(this).find(".caption").animate({
            "margin-left": "-200px"
        });
    }
);

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

What is the most effective way to identify mobile browsers using javascript/jquery?

As I develop a website, I am incorporating image preloading using JavaScript. However, I want to ensure that the preload_images() function is not called for users on slow bandwidth connections. In my experience, the main demographic with slow internet spe ...

Passing multiple variables to another page via AJAX

As I develop a website, I encountered an issue with resetting the password script on a specific page. To resolve this, I am utilizing AJAX to pass both the old and new passwords while aiming to display the outcome on the same page. The code snippet for th ...

Posts labeled with tags are not properly paginating

I've been working on a Django application that showcases posts created through Django's admin interface. These posts include tags implemented using django-taggit () The main page (home.html) is designed to display both posts and their respective ...

Having trouble getting PHP Ajax File Upload to function properly?

I am using Bootstrap and have a Form in a Modalbox. There is a Fileupload field, and I want to upload images. However, when I click the Submit button, the site seems to reload instantly and there is no file uploading... Below is my Ajax Script: <scri ...

Crashes within an HTML5 Canvas

Having recently started to explore Javascript and working with canvas elements, I've encountered a roadblock when trying to implement collision detection for the canvas walls. Typically, I have a small square drawn on the canvas that I can move aroun ...

Adjust and modify class when resizing the window

I've encountered a challenge with my Bootstrap Modal when trying to set the width to 750px on large desktops. When resizing the window to a smaller size, the modal loses its responsiveness. To tackle this, I added a class to the modal to give it a fix ...

What steps can I take to create a textbox that expands as more text is

Looking to create a unique textbook design that starts out with specific width and height dimensions, but expands downward as users type beyond the initial space. Wondering if CSS can help achieve this functionality? In a standard textbox, only a scroll ba ...

The CSS styles are not being applied to the PHP code

I seem to have a tangled mess of CSS / PHP / HTML to deal with. The issue I'm facing is that something works on one PHP script but not the other. Here's a snippet of my code: <?php if ($daten->getData_DB_User($get_page_num) != fa ...

Using JavaScript to parse an XML document on a WAMP server

I am a beginner in the field of web development and currently struggling with parsing an XML document using JavaScript on WAMP server. I know that both the web page and XML file need to be on the same server for it to work. I tried placing both the PHP and ...

Issue with footer not properly aligning on the page's bottom

In my current project, I am utilizing both angularjs and node js for development. Within my index.html, the views are being called in the following manner: <div ng-include="'views/header/header.view.html'"></div> <div ng-view styl ...

Evaluate the functionality of an Angular controller method that interacts with the Document Object Model (

We currently have an AngularJS controller that contains the following function: $scope.testMe = function() { return $('#test'); } So, how can we effectively test this function? We attempted a Karma test as shown below: describe(' ...

The fadeIn callback doesn't seem to function properly when triggered within the success function of jquery.ajax

Using AJAX, I fetch some data and prepend it to the body. Once displayed, I need to execute some client-side operations on this new element, such as rendering Latex using codecogs' script. Below is a snippet of my code: $.ajax({ /* ... */ success: fu ...

Is it possible to send an entire HTML table to the server and then update the database table with it?

Recently, I encountered an issue that has me stumped. Suppose I have a database table A with multiple columns and the server (PHP script) renders this data into an HTML table for the web client. Now, the challenge lies in allowing users to add/delete rows ...

Uploading a file to an MVC controller using AJAX is unsuccessful

When posting a form that contains file and HTML data, along with a function to get geocode, the controller only receives the data from the AJAX post but not the file. I suspect it may have something to do with the button used for posting, but I'm unce ...

FancyBox Integration with JW Player

I'm currently working on integrating JW Player within Fancy Box. Although Fancy Box is opening correctly with the specified dimensions below, I am facing an issue where the video does not display (this is occurring on a server). Below is an example li ...

How can jQuery be prompted to execute a query at regular intervals every X hours?

I'm facing some issues with events in PHPMyAdmin as I do not have super user permissions. Despite contacting my host for help, they have not been cooperative. As a solution, I am considering running a specific PHP query every hour. Is this feasible? ...

What is the best way to line up a Material icon and header text side by side?

Currently, I am developing a web-page using Angular Material. In my <mat-table>, I decided to include a <mat-icon> next to the header text. However, upon adding the mat-icon, I noticed that the icon and text were not perfectly aligned. The icon ...

What is the best way to format MySQL table data into rows and columns for display?

<?php mysql_connect('server', 'user', 'Pass'); mysql_select_db('add'); $query =mysql_query('select * from addimage'); while( $row = mysql_fetch_assoc($query) ) { echo "$row[url]"; } ?> This code ...

Utilizing HIGHCHARTS to effectively access PHP variables from a separate PHP file through Jquery/Ajax

I am facing an issue with accessing PHP variables from my main page in a PHP file called by AJAX. Is there a way to access these variables or should I include the PHP file in the one called by AJAX? PHP : variables.php <?php $myServername = "loca ...

Utilizing jQueryUI dialog along with gridview and updatepanel for a seamless user

Currently, I am utilizing jQuery to transform a column of hyperlinks within a gridview into UI dialogs. The gridview is housed in an updatepanel. When I click on one of the dialog's buttons, I trigger a __dopostback on the updatepanel to refresh the ...