Obtaining a webpage link from a div element with JQuery

I have been working on developing my own lightbox gallery and I think I'm almost there.

My gallery is currently set up as a grid, where each cell displays a preview image using an img tag with the url specified in the CSS. However, if I can't extract that URL from the CSS code, I resort to including an anchor tag in the HTML code. From there, I attempt to use this to retrieve the URL from the markup and insert it into the img src for the lightbox.

The functionality for clicking on a cell and showing the lightbox works fine, but I'm facing issues with integrating the HTML content into the lightbox.

Since explaining this concept might be tricky, please refer to the code snippet below for clarity.

$(document).ready(function($) {

$('.image-item').click(function(e) {
e.preventDefault();

var image_href = $(this).attr("href");

$("#lightbox").css("display", "block");
$('#content').html('<img src="' + image_href + '" />');

});

$('body').on('click', '#lightbox', function() {
$("#lightbox").css("display", "none");
});

});
#gallery {
height: 1200px;
position: relative;
width: 90%;
margin-left: 5%;
padding-top: 75px;
}

.image-item {
display: flex; 
justify-content: center;
align-items: center;
font-family: Thasadith;
font-weight: 400;
font-size: 18px;
letter-spacing: 3px;
color: #fff;
text-transform: uppercase;
background-color: steelblue;
}

#images-gallery {
display: grid;
height: 1150px;
grid-template-rows: repeat(4, 1fr);
grid-template-columns: repeat(3, 1fr);
grid-gap: 20px;
width: 100%;
}

.image-item.one {
grid-row: span 2;
grid-column: span 2;
}

.image-item.two {
grid-row: span 3;
grid-column: span 3;
}

.image-item.three {
grid-row: span 3;
grid-column: span 2;
}

.image-item.four {
grid-row: span 3;
grid-column: span 1;
}

#lightbox {
    position:fixed;
    top:0; 
    left:0; 
    width:100%; 
    height:100%; 
    background-color: black;
    opacity: 0.5;
    text-align: center;
    z-index: 2;
    display: none;
}

#lightbox p {
    text-align:right; 
    color:#fff; 
    margin-right:20px; 
    font-size:12px; 
}

#lightbox img {
    box-shadow:0 0 25px #111;
    -webkit-box-shadow:0 0 25px #111;
    -moz-box-shadow:0 0 25px #111;
    max-width:940px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="gallery">
<div id = "images-gallery">
            <div id="image-one" class="image-item">
            <a href="https://i.ibb.co/HXfG735/tattoo.jpg"></a>
            </div>
<!-- Remaining image items omitted for brevity-->
        </div>
</div>

    <div id="lightbox">
    <p>Click to close</p>
       <div id="content">
           <img src="#" />
       </div>
   </div>

Answer №1

You have attempted to access the href attribute of your img tag.

var image_href = $(this).attr("href");

The correct way is...

var image_href = $(this).children('a').attr("href");

$(document).ready(function($) {

$('.image-item').click(function(e) {
e.preventDefault();

var image_href = $(this).children('a').attr("href");

$("#lightbox").css("display", "block");
$('#content').html('<img src="' + image_href + '" />');

});

$('body').on('click', '#lightbox', function() {
$("#lightbox").css("display", "none");
});

});
#gallery {
height: 1200px;
position: relative;
width: 90%;
margin-left: 5%;
padding-top: 75px;
}

.image-item {
display: flex; 
justify-content: center;
align-items: center;
font-family: Thasadith;
font-weight: 400;
font-size: 18px;
letter-spacing: 3px;
color: #fff;
text-transform: uppercase;
background-color: steelblue;
}

#images-gallery {
display: grid;
height: 1150px;
grid-template-rows: repeat(4, 1fr);
grid-template-columns: repeat(3, 1fr);
grid-gap: 20px;
width: 100%;
}

.image-item.one {
grid-row: span 2;
grid-column: span 2;
}

.image-item.two {
grid-row: span 3;
grid-column: span 3;
}

.image-item.three {
grid-row: span 3;
grid-column: span 2;
}

.image-item.four {
grid-row: span 3;
grid-column: span 1;
}

#lightbox {
    position:fixed;
    top:0; 
    left:0; 
    width:100%; 
    height:100%; 
    background-color: black;
    opacity: 0.5;
    text-align: center;
    z-index: 2;
    display: none;
}

#lightbox p {
    text-align:right; 
    color:#fff; 
    margin-right:20px; 
    font-size:12px; 
}

#lightbox img {
    box-shadow:0 0 25px #111;
    -webkit-box-shadow:0 0 25px #111;
    -moz-box-shadow:0 0 25px #111;
    max-width:940px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="gallery">
<div id = "images-gallery">
            <div id="image-one" class="image-item">
            <a href="https://i.ibb.co/HXfG735/tattoo.jpg"></a>
            </div>
            <div id="image-two" class="image-item">
            <a href=""></a>
            </div>
                         ... (remaining HTML code)
        </div>
</div;

    <div id="lightbox">
    <p>Click to close</p>
       <div id="content">
           <img src="#" />
       </div>
   </div>

By the way, it's recommended to use data attributes for URLs instead of empty links to keep the DOM concise.

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

Changing from localhost:3000/admin to localhost:3000 within the local server

I am currently developing a node.js application. My goal is to have the homepage rendered after the admin successfully uploads data, transitioning from localhost:3000/admin to localhost:3000. I attempted to achieve this using the code snippet below: route ...

Displaying divs of varying heights in a line

I'm facing a challenge in creating floating divs, just like illustrated in the image provided in the link below. Currently, I am employing the float left property to align all the divs next to each other. The first picture displays the default layout ...

Troubleshooting issue with React mapping an array of items in a modal window

My state implementation is working perfectly fine, except for a minor issue with the modal window. Within the state, I have utilized objects that are normally displayed (you can refer to the screenshot here). Please pay attention to the "Open modal" butt ...

Is there a way to include multiple TinyMCE editors with unique configurations for each one?

Is it possible to incorporate multiple TinyMCE editors on a single page, each with its own distinct configuration settings? If so, how can this be achieved? ...

What causes the first button to be clicked and the form to be submitted when the enter key is pressed within a text

Start by opening the javascript console, then place your cursor in the text box and hit enter. What is the reason for the function "baz" being called? How can this behavior be prevented? function foo() { console.log('foo'); } function bar() ...

Adjust the color of the whole row in an HTML table by changing the background

I am struggling with styling my dynamic table that pulls data from an API. I have successfully generated the table and inserted rows using JavaScript. However, I am facing styling issues. The colors of my table rows are inconsistent (similar to when using ...

The functionality of Javascript is only accessible once you open the developer tools in Chrome

I am encountering a similar issue to the one discussed here: Why does JavaScript only work after opening developer tools in IE once? However, in my case, the problem arises in Chrome 44. The JavaScript code, particularly involving XHR and setInterval, f ...

My variable from subscribe is inaccessible to Angular2's NgIf

My goal is to display a spinner on my application while the data is being loaded. To achieve this, I set a variable named IsBusy to True before making the service call, and once the call is complete, I set IsBusy to false. However, I am facing an issue wh ...

The button within the modal does not function properly in Bootstrap 4, whereas it works perfectly in Bootstrap 3

I am currently working on a Laravel project where I am trying to use a button to show a modal. The modal contains a delete button, and while it works fine with Bootstrap 3, it is not functioning properly with Bootstrap 4. Here is the HTML code: <!- ...

Incorporating jQuery's 'each' method into a JavaScript function

https://i.sstatic.net/CdEkr.pngI'm dealing with a datatable that includes an 'amount' column. I've written a JavaScript function to format the numbers in the table by adding a currency symbol and separating thousands. However, I've ...

Challenges with communication between Ajax and Axis2

I've been struggling to obtain results from this specific Ajax command, but unfortunately, I have not been successful. $.ajax({ type: "get", url: "http://[localhost]:80**/*****/getdata.jws", data: 'method=s**& ...

What is the best way to selectively delete elements in d3.js?

I am faced with the task of manipulating a graph. I begin by opening and processing a file to extract the necessary modifications for the graph. These modifications are essentially node names stored within the text field of each node. My challenge lies in ...

Tips for detecting and handling add and remove events in react-select when adding or removing an item from the selection

updateSelection(value) { let removedItems = this.state.selected.filter(x => !value.includes(x)); console.log("Removed items: ", removedItems); this.setState({ selected: value }); } ...

Callbacks for AJAX responses that are asynchronous

After using AJAX in a limited and straightforward manner for some time, I find myself currently debugging a web application that heavily relies on JavaScript and JQuery for client-side coding. One issue that has caught my attention is the possibility of mu ...

Tips for optimizing loading speed by implementing pagination with HTML, jQuery, PHP, and MySQL on the go

I currently have a table with over 1400 rows, adding approximately 20 new rows every day, which is causing my page to slow down. My current approach involves using a while loop to generate table rows and columns, along with some JavaScript like the exampl ...

Exploring ways to dynamically alter templates using the link function in Angular.js

Recently, I developed a directive called widget which functions similar to ng-view, but the template name is derived from an attribute. app.directive('widget', function() { return { restrict: 'EA', scope: true, ...

What is the best way to horizontally align a div container that houses floating divs using CSS?

I am currently working on a layout that involves a main div container, div#title-box, being vertically and horizontally centered on the page. Inside this main container, I need three additional div containers: div#logo, div#title, and div#subtitle (see cod ...

Fetching images from a WikiJS API endpoint

I need help creating a GraphQL query string to retrieve page data from Wiki JS. Specifically, I am looking for a way to fetch the URL of the first image on the page. Unfortunately, I have been unable to find any information on how to do this in the documen ...

Extracting information from a child select element within a parent component with ReactJS

My child component includes a select form element that queries my API to populate a select box with the data. I am trying to pass the selected option back to the parent component using an OnChange function, so that I can send the data back to the server. H ...

I'm curious if it's possible to create a scrolling marquee on an SVG path with the use of HTML and CSS?

I am interested in creating a unique effect similar to what is showcased on this website or in the main menu of Colin McRae Rally 2.0. My goal is to generate a path and animate text along it, with the letters wrapping around to the start as they reach the ...