Increase the div id using jQuery

I've got this code snippet here and, oh boy, am I a newbie. How can I increase the number in the div using a jQuery script?


        if($res >= 1){
        $i=1;
            while($row = mysqli_fetch_array($qry)){

            echo   "<div class='imgAddCntr'> 
                       <div id='div".$i."' class='contentbox'>      
                        //content here
                       </div>
                       <div id='imgAdd'>
                         <img class='images' alt='CDL Training' src='".$imgLInk.$row['img']."'/>
                       </div>
                     </div>";   
                   $i++;
               }
             } 

I'm attempting to access the loop above and its associated div values


    $(document).ready(function() {

       $('#div1').hide();

           $(".images").hover(
                function () {
                  $("#div1").show();
                    },
                 function () {
                  $("#div1").hide();
            });
     });

Any guidance would be greatly appreciated

Answer №1

Learn how to target specific elements with jQuery using attribute selectors jQuery( "[attribute='value']" )

$(document).ready(function() {
    $('[id^=div]').hide();
    $(".images").hover(function() {
        $(this).closest('div.imgAddCntr').find('[id^=div]').show();
    }, function() {
        $(this).closest('div.imgAddCntr').find('[id^=div]').hide();
    });
});

Alternatively, consider using classes instead of ids for a more efficient approach

PHP

if ($res >= 1) {
    while ($row = mysqli_fetch_array($qry)) {
        echo "<div class='imgAddCntr'> 
                       <div class='contentbox'>      
                        //content here
                       </div>
                       <div class='imgAdd'>
                         <img class='images' alt='CDL Training' src='".$imgLInk.$row['img']."'/>
                       </div>
                     </div>";
    }
} 

jQuery

$(document).ready(function() {
    $('.contentbox').hide();
    $(".images").hover(function() {
        $(this).closest('div.imgAddCntr').find('.contentbox').show();
    }, function() {
        $(this).closest('div.imgAddCntr').find('.contentbox').hide();
    });
});

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

Trying to arrange HTML elements in a diagonal configuration while ensuring they are all uniform in size

My goal is to create an attractive splash page with diagonal, circular links that are all the same size. The <p>'s will function as the links, but I'm struggling to figure out how to make them all diagonal and uniform in size. I've ex ...

Utilizing jQuery to trigger a method in an ASCX page

There is a method to call a page function using jquery with the code below: $.ajax({ type: "POST", url: "Default.aspx/GetDate", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { // Repla ...

Ribbon design in LESS/CSS does not maintain its structure when resized in Google

My CSS/LESS ribbon is displaying perfectly in Firefox, but encountering issues in Chrome when resizing the window. At 100% zoom, everything looks good, but adjusting the zoom causes elements to become misaligned. To make it easier to troubleshoot, I' ...

How to get the clean URL in AngularJS without any parameters using $location

One issue I'm facing is related to the URL structure of my application. It currently looks like this: "http://host:port/mySystem?x.system" The addition of x.system in the URL was necessary due to a legacy application requirement, but now I need the U ...

When the text exceeds the designated block, it will be fragmented

I have always struggled with text elements not breaking when they exceed the boundaries of their parent element. I understand that setting a max-width of 100px will solve the issue, but it's not an ideal solution for me. I want the text to break only ...

How can we use forEach on an array or JSON data while sorting by the most recent date?

How can I reverse the order of data in the "forEach" loop so that the latest date is displayed first instead of the oldest to newest? var json = { // JSON data goes here } json.TrackingRecord.MovementInformation.Movement.reverse().forEach(function(it ...

Retrieve the user's information using their email address

I am attempting to retrieve "Registered user information" on my email address using the "mail()" function. The mail() function is functioning correctly and successfully sending the email to the specified email address, however, it is unable to retrieve the ...

I'm puzzled as to why my Contact Form is failing to send out emails

Looking to create an email send function in a pop-up on my website that can be accessed via the following link: The issue I'm facing is that while it redirects perfectly to the thank you message, the PHP implementation does not seem to work after the ...

Here is how you can include a date picker with the ability to choose the day, month, and year

Can someone help me create a datepicker with options to select days, months, and years? I've been able to find resources for selecting months and years, but I'm having trouble adding the option to choose specific days. If anyone has experience ...

Update the iframe located on a different webpage

I am looking to create a dynamic button feature on my website where clicking a button on page1.html will open a new page (portal.html) with an iframe displaying the URL specified in the button. The setup involves two main pages: page1.html, and portal.htm ...

react-query: QueryOptions not functioning as expected when utilizing userQueries()

When passing certain "query options" while using useQueries() to fetch multiple queries simultaneously, these specified "query options" do not get applied during query executions (e.g. refetchOnWindowFocus has a value of true but I want it to be false). F ...

What is the process for modifying two IDs simultaneously?

I'm struggling to include more than one ID in my CSS. I want the box border to have four different hover effects and three gradient buttons (e.g., play, pictures, etc.). Here is my HTML: <h2><a id="hover-1" href="">Hov ...

Obtain a collection of data- attribute values using jQuery

I am attempting to extract all the values from the data-hiringurl attributes found on this particular page . When I used var data = $("li").attr('data-hiringurl'); and var data = $("li").data('hiringurl'); in the console, an error mess ...

Getting error messages for form validation in CodeIgniter when using Fileupload via Ajax can be tricky. Here are

Hello, I am currently working on retrieving form errors for an input type file in CodeIgniter. I have created a Javascript code that utilizes Ajax to submit the details as shown below: var name = $("#name").val(); var des = $("#des").val(); var img=$("#fi ...

What is the best method for accessing the service response data when I am sending back an array of custom map with a promise as an object?

Sharing my code snippet below: function createObject(title, array){ this.title = title; this.array = array; } //$scope.objects is an array of objects function mapPromise(title, promise){ this.title= title; this.promise = promise; }; var fet ...

Social media icons condensed into a single line within a compact menu

I have come across a problem that I can't seem to solve. How can I display social icons in one line within a collapsed menu? I added the following code to my CSS file but nothing seems to have changed. Any suggestions or ideas would be greatly appreci ...

Is there a way to selectively include a filter in ng-repeat within a directive?

Utilizing an element directive across multiple views, the directive iterates through each 'resource' in a list of resources using ng-repeat="resource in resources". Different page controllers determine which resources are fetched from the API by ...

Is it necessary to validate input for a login form? Some may argue that it creates unnecessary overhead and introduces concerns about an excess of javascript

While working on input validation for my registration form, the idea of implementing it on my login form also crossed my mind. My login form only requires an email and password. I'm considering validating whether the email entered is a valid email add ...

Tips for preserving order of items in MVC framework

I have been working on organizing my carousel items and I need a sortable list view to help me choose the right format for the site. I managed to make the items sortable using this jQuery command: $(function() { $("#subsortsortable tbody.content") ...

I am struggling to showcase the values of character names stored within an array

I am currently developing a Library Express App and utilizing fake data to easily showcase the values on the screen. const PopularBooks = [ { id: 1, title: "Harry Potter", characters: [ { id: 1, name: "Har ...