Pass the dimensions of an image to fancybox upon clicking

I have a scenario where I need to open up different sized Fancybox frames (HTML) when different images are clicked. Each image has a corresponding Fancybox frame with specific height and width dimensions. How can I dynamically send the height and width values from the clicked image?

$("a.various").fancybox({
    beforeClose: function () {
        $("#gallery_spacer").remove();
    },
    openEffect: 'fade',
    openSpeed: 1500,
    closeEffect: 'fade',
    closeSpeed: 400,
    padding: '0',
    width: 660,
    height: 700,
    maxWidth: 660,
    maxHeight: 700,
    fitToView: false,
    autoSize: false,
    closeClick: false,
    autoScale: 'false',
    autoDimensions: 'false',
    transitionIn: 'true',
    transitionOut: 'true',
    type: 'iframe',
    openEffect: 'fade',
    helpers: {
        overlay: {
            css: {
                'background': 'rgba(255, 255, 255, 0.0)'
            }
        }
    }
});


$("a.various1").fancybox({
    beforeClose: function () {
        $("#gallery_spacer").remove();
    },
    openEffect: 'fade',
    openSpeed: 1500,
    closeEffect: 'fade',
    closeSpeed: 400,
    padding: '0',
    scrolling: 'no',
    width: 660,
    height: 1870,
    maxWidth: 660,
    maxHeight: 1870,
    fitToView: false,
    autoSize: false,
    closeClick: false,
    autoScale: 'false',
    autoDimensions: 'false',
    transitionIn: 'true',
    transitionOut: 'true',
    type: 'iframe',
    openEffect: 'fade',
    helpers: {
        overlay: {
            css: {
                'background': 'rgba(255, 255, 255, 0.0)'
            }
        }
    }
});

Here is an example of the HTML structure:

<li><a class="various1 fade " href="FOOTWEAR_SUB_PAGES/MERCURIAL_SUPERFLY.html"><img src="MAIN_IMAGES/MERCURIAL_SUPERFLY-2.jpg"  border="0" /></a></li>
<li><a class="various2 fade " href="FOOTWEAR_SUB_PAGES/AIRMAX_MOTO.html"><img src="MAIN_IMAGES/AIRMX-22.jpg"  border="0"  /></a></li>

Answer №1

If you want to make all your links fancybox-enabled with just one script, you can utilize HTML5 attributes like data-* to specify the width and height individually.

An example of how you can do this in your HTML:

<li><a class="fancybox" data-width="660" data-height="700"  href="FOOTWEAR_SUB_PAGES/MERCURIAL_SUPERFLY.html"><img src="MAIN_IMAGES/MERCURIAL_SUPERFLY-2.jpg"  border="0" /></a></li>
<li><a class="fancybox" data-width="660" data-height="1870" href="FOOTWEAR_SUB_PAGES/AIRMAX_MOTO.html"><img src="MAIN_IMAGES/AIRMX-22.jpg"  border="0"  /></a></li>

To retrieve the size for each link using the fancybox beforeShow callback, you can use the following code snippet:

beforeShow: function () {
    this.width  = $(this.element).data("width");
    this.height = $(this.element).data("height");
}

In this code snippet, $(this.element) references the clicked element.

You can refer to the JSFIDDLE for a live example.

It's important to note that some API options commented out in the fiddle are not valid in version 2.x (they were for v1.3.4 and are not compatible).

Answer №2

To retrieve the dimensions of the image, you can use the following code:

let width = $("img.myImage").width();
let height = $("img.myImage").height();

Answer №3

When loading content into an iframe, it becomes challenging to obtain the necessary dimensions for fancybox until after the html is fully rendered within the iframe.

To address this issue, you can utilize the onComplete function to resize the fancybox once the html has been rendered as explained in more detail here.

For your specific scenario, you can implement the following:

$("a.various").fancybox({
            beforeClose: function () { $("#gallery_spacer").remove(); },
            'onComplete' : function() {
                $('#fancybox-frame').load(function() {
                    $('#fancybox-content').height($(this).contents().find('body').height()).width($(this).contents().find('body').width());
            });
            openEffect: 'fade',openSpeed: 1500,closeEffect: 'fade',closeSpeed: 400,'padding': '0','width': 660,'height': 700,
            maxWidth: 660,maxHeight: 700,fitToView: false,autoSize: false,closeClick: false,'autoScale': 'false','autoDimensions': 'false',
            'transitionIn': 'true','transitionOut': 'true','type': 'iframe','openEffect': 'fade',
            helpers: {overlay: { css: {'background': 'rgba(255, 255, 255, 0.0)'}}}});

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

Error in Java Spring occurs when the webpage is loaded due to a Maven compilation error in

Every time I execute the program, an error occurs: 2022-11-25 18:31:53.591 ERROR 8435 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request proces ...

Modifying Django: What is the process for altering the HTML representation of a Django form component?

I've got a set of three select drop down boxes for selecting a date of birth. Here's how my Django template displays it: <label>Date of birth</label> {{ reg_form.date_of_birth }} However, I need to customize the HTML structure for e ...

When attempting to remove an object from the scene, an error occurs stating that children[i]

Is there a way to remove an object from the scene? removeObjectFromScene = (position) => { this.scene.traverse((child) => { if (child.isGroup && child.userData.position) { if (child.userData.position.equals(position)) ...

Unable to remove click event from nested <li> element

I have a function that enables the expansion and collapse of an unordered list by clicking on the list item. However, the issue arises when the lowest level LI contains a table with a checkbox, as clicking on the table triggers the display of the parent li ...

When retrieving items from an object store in HTML, the result displayed is often [object Object]

Currently, I am in the process of iterating through all objects within the object store named "tasksStore". However, when attempting to display these objects in my HTML, only [object Object] is returned. Even if I try to specify a specific part of the obje ...

The WP Sidebar jQuery Toggle feature is malfunctioning

The jQuery toggle functionality in the right sidebar of my website ceases to work when I remove the script src code. Despite other plugins on the site loading jQuery, the toggle feature stops working altogether. Check out my website here: To open the tog ...

What is the process for invoking a server-side C# method from AJAX while transmitting parameters to the function using CommandArgument?

My C# method is responsible for saving data to a SQL Server. It is called from an Onlick event, passing parameters using CommandArgument. Here is an example: <asp:LinkButton runat="server" onClick="save" CommandArgument='<%# Eval("post_id").ToS ...

Incorporate a hanging indent within the text enclosed by the <li> element

(revised multiple times to enhance clarity) Disclaimer: I did not create the HTML code. Below is the structure of the HTML (please note that the links and text following them are on the same line): <li> <strong>Heading of section</str ...

Showing outcomes from various API requests

I have encountered an issue while making two API calls to a backend server and trying to display both responses in JSON format to the user. Strangely, alert 2 is showing as 'undefined' when I check the console, while alert 1 works perfectly fine. ...

I am having trouble getting Highcarts to load the JSON data

I am currently in the process of utilizing Highcharts to generate a chart. The JSON output I have is in standard format and was generated using PHP's json_encode() function. Below is the JSON output: [["2015-07-13 16:41:05","3"],["2015-08-15 16:41:05 ...

Leveraging HTML5 Semantic Tags in Harmony with the BEM Approach

Would it be beneficial to utilize HTML5 semantic elements alongside BEM? For example, is <header class="header header--full"> <nav class="header__nav">...</nav> </header> Acceptable or should I opt for divs instead? ...

Troubleshooting: JavaScript Bookmarklet Fails to Execute on Certain Websites

Recently, I created a unique bookmarklet that functions flawlessly on some websites, but unfortunately fails to work on others. Interestingly, even when it doesn't work, the script is still added to the bottom of the page; however, only a portion of t ...

What is the best method for utilizing the CSS :target selector in order to generate a versatile modal box?

I am looking for a way to display my vast collection of proverbs from an endangered language without overcrowding the page. I have implemented a modal box solution using CSS :target selector, which expands a hidden div element when clicked on. However, I n ...

Rails implementation of a star-based rating system

For my latest project, I've incorporated a rating system that can be found here. The integration was successful and it's functioning as intended. In this project, I have two models: Casino and Rating. The relationship is set up such that Casino h ...

Refreshing AvForm in React.js to clear entered data

Currently, I am utilizing AvForm within React JS to handle form submissions. However, I am encountering an issue where the form does not reset after submission; instead, it retains the previous input values until the page is manually refreshed. Here is a ...

You are unable to declare a variable within an AJAX function using jQuery

Struggling to update variables within the AJAX function? For example, if there is a variable declared outside like var myName = "My name is Kenny"; and inside the AJAX function you attempt myName.replace("Kenny", "Earl"); Upon running console.log(myNa ...

Tips for customizing ngTable with expandable detail panels

I am currently working on styling a layout using ng-table, which includes a table within each row. The expanding functionality in Angular is implemented as follows: <tr ng-if="org.expanded" ng-repeat-end> <td></td> <td></td& ...

What method can I use to identify the most widely-used edition of a specific npm module?

While the npm registry does provide metrics on the most depended packages, have you ever wondered if it's possible to determine the most popular version of a specific package? For example, as a user considering upgrading to react-router^4.0.0, wouldn ...

Obtain the file path and store it in a variable right after using fs.writefile

Can anyone assist me in obtaining the file path of the created file in the following code snippet? I am passing a barcodeSourceNumber as a parameter and expecting the file path as the return value. pathToFile = generateBarcodeImage('123456789'); ...

What is the process for creating a customized object using Serialized format?

In order to convert a few serialized form elements into a JSON object, I created a function. However, when the fieldName is included in the JSON object, it appears as "fieldName" instead of the actual field name such as "PositionId" or "Series". Although ...