Modifying a variable when a specific number of elements are clicked using jQuery

I have created a script for my portfolio that is functional but I want to streamline it so that I only need to edit the HTML, not the script itself.

The main requirements for the code are:

  1. Count the number of <img> tags within the element with id #thumbs
  2. Retrieve the SRC from the thumbnail image or the HREF if available from an anchor tag around the thumbnail
  3. Store either the modified SRC (with "_sm" removed) or the HREF in a variable

Once these variables are set up, I believe I can easily make the script fully functional. However, I am unsure of how to get the script to read this information and dynamically adjust based on it.

Below is the current code snippet:

<script type="text/javascript">
        $(document).ready(function() {
            // last clicked thumbnail
            var last = "idthisperson";

            // variables assigned based on IDs
            var graphic01 = "idthisperson";
            var graphic02 = "leo";
            var graphic03 = "water-fire";

            // test counting img tags within #thumbs
            var n = $("#thumbs img").length;        
            alert(n);

            // separate functions for each img ID click event
            $("#" + graphic01).click(function() {
                if(last != graphic01) {
                    $("#placeholder").before( "<img src=\"gallery/" + graphic01 + ".jpg\" />" );
                    $("#mask").css("marginTop","-=450px");
                    last = graphic01;
                }
            });

            $("#" + graphic02).click(function() {
                if(last != graphic02) {
                    $("#placeholder").before( "<img src=\"gallery/" + graphic02 + ".jpg\" />" );
                    $("#mask").css("marginTop","-=450px");
                    last = graphic02;
                }
            });

            $("#" + graphic03).click(function() {
                if(last != graphic03) {
                    $("#placeholder").before( "<img src=\"gallery/" + graphic03 + ".jpg\" />" );
                    $("#mask").css("marginTop","-=450px");
                    last = graphic03;
                }
            });

        });
    </script>

And here is the accompanying HTML:

   <section id="portfolio">
    <section id="mask">
        <img src="gallery/idthisperson.jpg" />
        <div id="placeholder"></div>
    </section><!--/#mask-->
</section><!--/#portfolio-->
<section id="thumbs">
    <a href="gallery/idthisperson.jpg"><img id="idthisperson" src="gallery/idthisperson_sm.jpg" /></a>
    <a href="gallery/leo.jpg"><img id="leo" src="gallery/leo_sm.jpg" /></a>
    <a href="galelry/water-fire.jpg"><img id="water-fire" src="gallery/water-fire_sm.jpg" /></a>
    <a href="gallery/idthisperson.jpg"><img src="gallery/idthisperson_sm.jpg" /></a>
</section><!--/#thumbs-->

Additional Notes:
Live demo:
How can I utilize the transitionend JavaScript event to ensure my CSS3 transition completes before triggering the next thumbnail click?
For complete code details, best to view the source of the live demo.

Answer №1

One way to handle <a> tags in the thumbs div is by creating a function that utilizes the href attribute of the link as the name of the graphic.

$("#thumbs a").click(function() {
    var graphic = $(this).attr('href'); //get the href of the anchor
    if(last != graphic) {
        $("#placeholder").before( "<img src=\"" + graphic + "\" />" );
        $("#mask").css("marginTop","-=450px");
        last = graphic;
    }
    return false; //prevents redirect
});

An update has been made to align with the changes in the original question.

Answer №2

1. Calculate the number of image tags under #thumbs

numOfImgTags = $('#thumbs img').length;

2. Retrieve the source (SRC) from the thumbnail, or a possible HREF from an anchor (A tag) surrounding the thumbnail

imgSrc = $('#thumbs img').attr('src');
aHref = $('#thumbs img').parent('a').attr('href');

3. Store either the modified SRC (removing _sm from the file name), or the HREF in a variable

imgSrcVariable = imgSrc.replace('_sm','');
//the aHref variable already accomplishes this

Will this information help you get started?

Answer №3

Give this a try:

let count = 0;
let imageArray = [];

$('#thumbs img').each(function(){
    count++; //increment the image count
    imageArray[count] = $(this).attr('src').replace('_sm',''); //store the source in the appropriate index, leaving index 0 empty for clarity
});

Now you can access the source for image number x by using: imageArray[x];

Hopefully this solution works for you!

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

Display the dropdown selection

I am trying to customize my dropdown menu so that when I hover over the main menu item (Sample Page), only the About submenu is displayed, not all of the dropdown menus. li.menu-item.dropdown .dropdown-menu { position: absolute; top: 70px; visibil ...

Having issues with reading files in PHP using AJAX? Explore alternative methods for downloading files seamlessly

I need to store a value in a txt file and allow the user to download it. Currently, the value is successfully written to the txt file, but the readfile function does not execute, preventing the download from starting. The PHP code is on the same page as ...

When the page size decreases, implement a media query to rearrange div elements in a vertical order

I am currently facing a design challenge with a website component that appears as one solid inline block. While it looks okay on a normal-sized screen, things start to look strange when the screen size decreases. I have attempted using a media query to adj ...

Incorporating a picture backdrop into a button element in a React Typescript component

I am working on a React project with TypeScript and using a Material UI library. I am trying to set a background image for a button, but when I use src or imageURL, it gives me a TypeScript error. The CSS style also does not show the picture. Here is my ...

Having difficulty selecting a cloned div using jQuery

I am in the process of creating a dynamic menu that switches out sub-menus. <nav id="main-menu"> <div id="categories"> <a id="snacks" class="categ">Snacks &amp; Sweets</a> <a id="pantry" class="categ"> ...

What is the best way to attach an image to the image section coming from the backend in vue.js?

I have developed a frontend page that displays a list of books, with the data coming from the backend. The backend response includes image files, and I am struggling to bind these images to the image section of my template. I have the image paths from the ...

Image broken on default bootstrap navbar

On my computer where I am developing a Ruby on Rails app, I have a relative link to an image. To customize the style, I am using Bootstrap and have used their code to source the image for the top left brand placement. You can view the Bootstrap link here. ...

An element in CSS that has a position of fixed and a width of 100% surpasses the dimensions of its

My element has the CSS properties position:fixed and width:100%, causing it to be larger than its parent elements. Despite the complexity of my code, I have attempted to simplify it for better understanding. Below, you can see that the green box exceeds ...

Adjust the width of Google chart to 100% automatically when the page is resized in Angular version 4 or higher

My application has numerous responsive wrappers on the site, each predefined from an API and containing a Google chart. The problem is that when the page initially loads, the charts are rendered at a specific size, and resizing the window only affects the ...

Is there a way to adjust the height overflow using a percentage?

I have a coding dilemma here where I am attempting to make the SearchLocationCards overflow. It seems to work fine with 'px' and 'vh' values, but the '%' value doesn't seem to have any effect. How can I adjust the height ...

The fixed sidebar refuses to pause before reaching the footer

I am facing an issue while building my blog. I am trying to figure out how to make my sidebar widget sticky and stop scrolling before reaching the #footer section. My widget is overlapping my footer and it would be really helpful if someone could assist m ...

Enhance the visual appeal of incoming data using Angular Material's dynamic styling feature

Is it possible to enhance the text with some CSS styling to make each item stand out like in this example: https://i.stack.imgur.com/kSyZE.png I prefer not to include a cross button or provide users with the option to add tags. The data is coming from a R ...

Prevent the table cell width from expanding beyond the content size

Is there a way to achieve this layout without relying on Javascript? Imagine having a <table> with an unknown width in the first column. The overall <table> width is set to 100% to allow other columns to resize accordingly, but is it possible ...

Stopping jQuery fadeOut from setting the display property to 'hidden'

I am currently working on a project that involves creating a lightbox effect. I am using jQuery's fadeIn and fadeOut functions to display enlarged div elements. However, I have encountered an issue - when I use fadeOut on the enlarged div, the smaller ...

Enlarging the current division while reducing the size of the others when hovering

Currently, I am working on a school project that involves creating a slideshow on a webpage. However, I have reached a point where I am unsure of how to proceed. Here is the progress I have made so far: body { background-color: #252525; } #wrapper { ...

JQuery UI Autocomplete: Results, Ctrl + A and Delete

I am currently designing a form that allows users to add members to a project. Only members with existing profiles in the system can be added. The form includes an input field for the member's name and a select box for their position, which is initial ...

Stop the time-dependent function from executing within a specific condition

Here is the code snippet I am currently working with: var w = $(window); var $navbar = $('.navbar'); var didScroll = false; w.on('scroll', function(){ didScroll = true; }); function AddScrollHeader(pxFromTop) { setInterval(fun ...

Encountered an issue when trying to send a PHP email using AJAX

I need some assistance regarding the email sending issue. It seems that there is an error in my PHP code as I am unable to send emails. The configuration for php mail needs to be checked since the script always goes to the else part. <?php if($_POST) ...

Disallow users from closing the tab or browser window

Is it feasible to create a loop on window.onbeforeunload that opens the current page repeatedly upon tab exit? Take a look at the code below - it works, but browsers may block it as a popup. window.onbeforeunload = function(e) { window.open(do ...

deactivate a vessel, causing all of its contents to be rendered inactive

Hi there, I am in search of a container that has the ability to disable all elements within it, not just inputs but also images and other elements without the disabled property. I do not want to hide the container, but rather disable it. Do you know if suc ...