Show random images of different sizes by employing jquery

I am seeking a solution for my webpage which currently loads a random image from an array and centers it using negative margins in CSS. While this method works fine with images of the same size, I am looking to modify the code so that it can handle images with different dimensions.

Is there a way to determine the height and width of an image at the array stage and then pass that information to the CSS/HTML to centrally position it? Below is the code I have been working on – any assistance would be highly appreciated.

Code Snippets:

#content {
margin-top: -206px;
margin-left: -290px;
position: absolute;
top: 50%;
left: 50%;
width: auto;
height: auto;
}

<div id="content">
<img class="shuffle" src="" width="580" height="413" border="0" alt="" />
</div>

JQuery:

$(document).ready(function() { $('.shuffle').randomImage({path: 'images/'}); } );

(function($){ $.randomImage = { defaults: { path: 'images/', myImages: [ 'image01.jpg', 'image02.jpg','image03.jpg', 'image04.jpg', 'image05.jpg' ] } }

    $.fn.extend({ randomImage:function(config) { 
            var config = $.extend({}, $.randomImage.defaults, config); 
            return this.each(function() {
                var imageNames = config.myImages;
                var imageNamesSize = imageNames.length;
                var randomNumber = Math.floor(Math.random()*imageNamesSize);
                var selectedImage = imageNames[randomNumber];
                var fullPath = config.path + selectedImage;
                $(this).attr( { src: fullPath, alt: selectedImage } ); 
            }); 
        }
    });
})(jQuery);

Answer №1

Here is the solution:


...
var fullPath = config.path + selectedImage;
var image = new Image();
image.src = fullPath;
var size = image.width;
alert(size);
...

I have successfully tested this code in Firefox version 3.6.

I hope this explanation proves useful. Thank you!

Answer №2

Appreciate the guidance; it set me on the correct path. Here's the code I came up with that functions well in Firefox 5 and Safari 5. While not the most elegant solution, it gets the job done – perhaps someone can find a way to simplify it further.

Edit 19.07.11: Taking inspiration from this example, I managed to streamline the code significantly. However, I believe there is still room for improvement in terms of simplification.

html:

<div id="wrapper">
    <div id="content"></div>
</div>

jquery:

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

    var images = ['image01.jpg', 'image02.jpg','image03.jpg','image04.jpg','image05.jpg'];

    $('<img src="images/' + images[Math.floor(Math.random() * images.length)] + '">').appendTo('#content');

    (function($) {
        $.fn.verticalAlign = function() {
            return this.each(function(i) {
                var oh = $(this).height();
                var wh = $(window).height();
                var middle = (wh - oh) / 2;
                if (middle > 0) {
                    $(this).css('margin-top', middle);
                } else {
                    $(this).css('margin-top', 0);
                }
            });
        };
    })(jQuery);

    $(window).load(function() {
        $("#content").verticalAlign();
        var showContent = function() { $('#content').fadeIn(750); };
        setTimeout(showContent, 100);
    });

    $(window).bind('resize', function() {
        $("#content").verticalAlign();
    });
});

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

I am struggling to retrieve the temporary name of an image upload with PHP and AJAX

I am working on a project where I need to extract the temporary name of an uploaded image using PHP and Ajax. While I have successfully retrieved the file name of the uploaded image, I am facing difficulties in getting the temporary name. Below is the snip ...

Rearrange the sequence of numbers using JQuery when an HTML element is deleted

I'm currently working on a simple functionality where I have 5 rows, each with its own number. So initially, the rows are numbered from 5 to 1. If I remove a value like 3, the sequence should adjust to 4, 2, 1, indicating that I now have only 4 rows ...

Solving the CSS Trick: Responsive Data Table (featuring inline editing) Display Glitch

In my quest to create a responsive table with inline editing, I turned to Chris's guide at CSS-Tricks (check it out here). To see how it all comes together, take a look at this Plunker demo. On mobile screens, the responsiveness is on point. https: ...

What steps should be taken to enlarge a checkbox within a table?

I need help with resizing the checkboxes that are inside a table. When I try using width:###px; height:###px;, it only seems to make them smaller, not bigger. Even when I set the values higher than the default size, the checkboxes stay the same while the d ...

Preview and crop your image before uploading

Currently, I am working on developing a form that will enable administrators to upload an image. The aim is to allow them to preview the image before uploading it, displaying it at a specific size and providing the option to click on the image to open an i ...

Is there a way to properly size and align an inline image within a dynamically resizing DIV element?

I am working on a fluid layout where I have a div that always matches the height and width of the browser window, regardless of resizing. Essentially, this div is set to be 100% height and width of the browser window. Inside this div, I have an image that ...

Using Unobtrusive Ajax, learn to integrate data-ajax-confirm with sweetalert

Here is an example of a form using AJAX: <form method="post" data-ajax="true" data-ajax-method="post" data-ajax-complete="completed" data-ajax-confirm="Are you sure you want ...

Experimenting with applying jquery .slideDown() to multiple classes in order to create dynamic animations

I am facing an issue while using .slideDown() with multiple classes. I want only one class to toggle/dropdown at a time, but currently when I press the button, all classes show up instead of just the one I want to display. How can I achieve this? Here is ...

Attempting to align content in the middle of the page across all web browsers

I need assistance with centering all the content on my website across different screen sizes and browsers. Currently, everything appears off-center and aligned to the left on various screens I have tested. You can view the HTML and CSS code in this link. H ...

The javascript function in my file isn't being triggered by jquery

In my ASP.NET MVC project, I am facing an issue with a jQuery function in a JavaScript file located under the Scripts folder. This function is supposed to fill a textbox with the selected value upon clicking a dropdown, but for some reason it is not workin ...

What is the best way to ensure that a Flex div and its child images stay confined within the boundaries of its parent container?

I'm struggling to create a responsive grid of images. I can't get the images to be both responsive with max-height and max-width, while also making sure the parent div takes up their full width. On the other hand, if I make the parent div the cor ...

Tips for arranging elements in proper order following a rotation

Having trouble aligning rotated divs? Let's say we rotate .straight by 30deg, and now we want to find the new offset coordinates of its bottom right corner. This way, we can perfectly match up the bottom left corners of .curve with this new coordinate ...

Jumping transitions in thumbnail images

Could you please visit I've noticed that when hovering over the thumbnails in the last column, the images jump a bit after transition, especially in Firefox. Do you have any suggestions on how to resolve this issue? ...

Refresh the page only when on the initial page of the pagination

I've been utilizing this jQuery code with AJAX for pagination purposes. Currently, I am fetching data from a PHP file that displays limited information. Here is the index file snippet: <script type="text/javascript"> $(document).ready(fun ...

JQuery Scroll Spy Implementation

I have structured the page with a header at the top and 3 columns below. The left column contains a menu, the middle column is a text container, and the right column is another section. As the page scrolls up, the menu becomes fixed in position which func ...

The functionality of displaying a loading image when the Upload button is clicked has encountered a glitch and

I am looking to add a feature that displays a loader when a user uploads a file by clicking on a button. The loader should be visible while the data is being processed in the background. To achieve this, I have included a div as shown below: <div id=" ...

Finding the nearest span value upon clicking through a specific class

Whenever a user clicks on a hyperlink, my goal is to locate the nearest span element with a specific class and retrieve the text within that class. As of now, it is only returning blank text: Here is the provided HTML code snippet: <div class="plan re ...

Angular 7 - Creating tooltips with multiline text

I've utilized template strings to create a multi-line string. toolTip = ` ${Test} : ${number} ${Test} : ${number} ${Test} : ${number} ${Test} : ${number} ${Test} : ${number}}`; The issue I'm facing is that w ...

Issue regarding the sidebar's top alignment

Having trouble with the positioning of this sidebar. It seems to be hanging slightly over the top edge instead of aligning perfectly with it. Here's how it looks: enter image description here. CSS CODE: https://pastebin.com/RUmsRkYw HTML CODE: https ...

Navigating through jQuery UI tabs with multiple navigation items

I am currently working on implementing a jQuery function with dual navigation menus. Currently, I have the traditional navigation menu structure: $( "#tabs" ).tabs(); <ul class="nav-tabs"> <li><a href="#tab-0">Tab 1 - ref</a> ...