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

What is the best way to pass the reference of the p tag every time the button is clicked?

This is the code I used to create a button: <button type="submit" id="likebtn" onclick="likedpost(this) " data-postid="<%=blog._id%>" data-author="<%=user.username%>">Like</button> ...

Discovering the reason behind a DOM element's visual alteration upon hovering: Where to start?

Visit this page, then click on the next button to navigate to the time slots section. As you hover over any time slot, you will notice a change in appearance. Despite inspecting Chrome's developer tools, I was unable to locate a style with a hover dec ...

Building a loading bar using dots

<span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> <span class="dot">< ...

Missing Bootstrap 3 Options Menu trip away

I created a table with 4 columns using the Bootstrap 3 grid system. Instead of utilizing the col-xs-* classes, which work well on mobile devices, I opted for the col-md-* classes. This decision was based on my preference to have larger and more visible ico ...

Using JQuery to toggle checkbox status after receiving an Ajax response

I am encountering a small issue with my code. I have a function that requires an AJAX call to load data on the page, which then populates checkboxes (which is working fine). My goal is for a checkbox to trigger an AJAX request when clicked, causing a valu ...

What is the best way to target an HTML attribute using jQuery?

I have customized a Textbox by adding a special attribute: <asp.TextBox MyCustomAttribute="SomeValue"><asp.TextBox> Now, I want to retrieve this value from within an AJAX success function. Please note that I have excluded irrelevant attribut ...

Synchronize Magento cart totals and items using AJAX

Hello there, I am currently developing a custom AJAX cart for Magento and I prefer not to use any pre-made extensions. I want this cart to be unique and tailored specifically to my needs. Could you please advise me on the best method to retrieve importan ...

Using JavaScript to submit the value of a checkbox

I'm currently working on a form submission using JavaScript that includes both text input and two checkboxes. <script> function SubmitFormData() { var preferredLocation = $("#preferred_location").val(); var relocation = []; ...

What is the best way to transfer an argument from a parsed JSON value to an onclick function?

In our dataset, we have a specific table that contains valuable information. My main objective is to transfer an argument extracted from parsed JSON data to a separate JavaScript function known as newStory(value['stories']) using the onclick meth ...

HTML code causing an Ajax post request to return a null value

How can I send JSON data from HTML to PHP using the Ajax post method? I have looked at various resources like this and this but so far, I am only getting a null return value. Other similar questions have not been helpful either. HTML (jQuery Ajax): $(&apo ...

Which specific jQuery functionality was made visible?

When it comes to jQuery, how is it exposed? // Expose jQuery to the global object window.jQuery = window.$ = jQuery; However, there are in fact two versions of jQuery: var jQuery = (function() { // Define a local copy of jQuery var jQuery = function( s ...

Unsuccessful retrieval of hidden property's value following ajax request

While using my web app, I encountered an issue with my ajax script that submits form data to a different div based on an input tag within the submitting form. Everything works smoothly until the moment the ajax script needs to read the returned ajax data. ...

When you add the /deep/ selector in an Angular 4 component's CSS, it applies the same style to other components. Looking for a fix?

Note: I am using css with Angular 4, not scss. To clarify further, In my number.component.css file, I have: /deep/ .mat-drawer-content{ height:100vh; } Other component.css files do not have the .mat-drawer-content class, but it is common to all views ...

Ways to create two distinct "on click" actions for a single image to execute two distinct tasks

Clicking on an image will open a slider showing all images before filtering. Once filtered, only the selected images will be displayed in the slider. <div class="gallery row" id="gallery" style="margin:0;"> <!-- Grid column --> <div ...

Using JQuery to Evaluate HTML into an Element

When working with PHP pages, I often need to fetch data from another source and populate an input or textarea field. However, I encounter issues when dealing with HTML tags and apostrophes. In my experience, passing around HTML content using JavaScript ca ...

Error: Property 'html' is undefined - AJAX response must be displayed only in a specific div

I encountered an issue: Uncaught TypeError: Cannot read property 'html' of undefined I am working on implementing a voting system for each video on my webpage from a database. I have successfully integrated it using AJAX, but the problem is ...

jqGrid is throwing an error: undefined is not recognized as a function

Currently, I am in the process of trying to display a basic grid on the screen. Following the instructions provided in the jqGrid wiki, I have linked and created scripts for the required files. One essential css file, jquery-ui-1.8.18.custom.css, was missi ...

When located at the bottom of a page, the Div element fails to display

I need some help with my javascript code. I am working on creating a scrollable panel that closes when scrolled and reveals a #toTop div when the bottom of the page is reached. Below is the function code I have written, but for some reason, the #toTop div ...

Is it possible to refresh the page without using a hashtag and stay on the same page in AngularJS

Is it possible to refresh my view from the navigation bar without displaying the server folder? I have the html5Mode activated: if(window.history && window.history.pushState) { $locationProvider.html5Mode(true); } ...

What is the complete list of features that ColorTranslator.FromHtml() supports and what are the reasons behind its departure from traditional CSS color interpretation guidelines

I'm looking to enhance an API by providing users with the ability to specify the color of something. I want it to accept various representations of colors, such as hex codes and CSS colors. Initially, I thought that ColorTranslator.FromHtml() would fu ...