Using a function as a parameter for the background-image url in jQuery

Can I send a function as an argument to the background-image URL parameter in jQuery?

Is it possible to achieve something similar to this example...

jQuery('<span>').css('background-image', 'url(' + check_file_type(value.Name) + ')');

The function provides the proper format for the URL address, but perhaps I am not invoking it correctly.

    function get_extension(filename) {
        return filename.split('.').pop().toLowerCase();
    }

    function check_file_type(file) { 
        switch(get_extension(file)) {
            //if .jpg/.gif/.png do something
            case 'jpg': case 'gif': case 'png':
                return '{!URLFOR($Resource.images, 'images/doctype_image.png')}';
                break;
            //if .zip/.rar do something else
            case 'zip': case 'rar':
                return '{!URLFOR($Resource.images, 'images/doctype_zip.png')}';
                break;

            //if .pdf do something else
            case 'pdf': case 'pptx':
                return '{!URLFOR($Resource.images, 'images/doctype_pdf.png')}';
                break;
        }
    }

Answer №1

Yes, you are capable. The function should output a string and you're all set.

Answer №2

Yes, it is definitely doable to have the function return a string value. I noticed that the JQuery code you are utilizing is responsible for creating a new element. Is this the desired outcome you are aiming for? In my scenario, I assumed the presence of an already existing span element.

function initialize() {                    
    var data = {};
    data.label = "Hi";

    $('span').css('background-image', 'url(' + determine_file_type(data.label) + ')');
}

function determine_file_type(label) {
    return "http://" + label + ".png";
}

initialize();

Here's a small JSFiddle showcasing the concept in action. Please note that the file type checking function used in my demonstration doesn't actually verify any file types.

Answer №3

The solution was discovered by me, it turned out to be caused by an additional curly bracket...

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

Troubleshooting CSS Navigation Drop Issue Specific to Google Chrome. Seeking Feedback on Rails Tutorial Experience

I'm currently working my way through the amazing Rails Tutorial and have encountered a problem with the Navigation bar dropping down into the body of the page, but this issue only seems to occur in Chrome (I'm using Linux, Ubuntu 10.10). I'v ...

Using jQuery Ajax and PHP for Secure User Authentication

Hello everyone, I could really use some assistance right now. The issue I'm facing is that the error div is not showing the content I expect in the success function of my AJAX request. I've tried alerting the response, which returns true if the ...

I'm looking to create a redirect feature using a QR code that will direct users to a specific page within my Flutter app. How

When the user scans the QR code, they will be taken to a secret internal page that can only be accessed through this specific link. I attempted to use various libraries such as , but it did not achieve the desired outcome. ...

Extending the rules and requirements of VInput

Currently, I am utilizing Vue+Vuetify and facing the task of revamping a custom selector component. The existing code structure is as follows: <template> <v-autocomplete :id="id" v-model="internalValue" :clearabl ...

Generating unique ID's for data posting in PHP and JavaScript

I've developed a dynamic form that includes an "add more" button to generate an XML file for data import purposes. Users can fill out the form and add as many entries as needed by clicking on the "add more" button. The inputted data is then processed ...

Top method for customizing w2ui grid appearance

While utilizing the w2ui grid to showcase data in a table, I've found it to be quite effective. However, I'm not entirely happy with the appearance of the table itself. Are there any methods available for styling the table that don't involve ...

Is it possible to locate both the child and parent elements by their class names simultaneously using WebDriver?

When conducting a search on eBay that returns more than 50 listings, such as this example, the site displays the results in either grid or list format. Using the WebDriver tool, I am extracting prices by their class name: https://i.stack.imgur.com/dGNzw. ...

Assign the values from the axios response to variables within the exported const

Currently, I am incorporating axios into my vue.js application to perform an HTTP POST request and retrieve some variables for a vue-echart. However, I have encountered a bit of a roadblock in determining the most effective approach. The snippet below is ...

Unable to pass an event parameter using my this.handleChange function in react-native

Encountering an issue with the error message "undefined is not an object (evaluating 'event.preventDefault)" It appears that I am unable to pass an event parameter to the handleChange function in my child component, which is being rendered in the par ...

Utilize HTML to resize image to fit within container

I've encountered an issue while working with Adobe Dreamweaver CS5. I added a swap behavior to an image in an html document, expecting it to pop up at its original size and restore on mouse out. However, the swapped image ends up filling the entire sc ...

Disappearance of Dom Css following implementation of jQuery Pagination in Wordpress widget

After developing a Wordpress widget for showcasing portfolios, I have successfully integrated features such as pagination, filter categories, and customizable post count per page. Everything works seamlessly with a custom PHP pagination system that I have ...

What is the best way to integrate HTML code within a JavaScript function?

I need the HTML code to execute only when a specific condition in JavaScript is met. Here is the JavaScript code: <script type="text/javascript"> $(document).ready(function () { if(window.location.href.indexOf("index.php") > -1) { ...

Exploring the creation of CSS animations using box-shadow effects

Looking to create a CSS animation where part of a line (200px) changes color like a gradient. Any ideas on how to achieve this effect? Below is the current code being used: * { margin: 0; padding: 0 20px; } h1 { text-align: center; } ...

Half of the sections will not stack on mobile devices

UPDATE I found and fixed a typo in the code, making adjustments to both the JSFiddle and this post to show the correction. The Headline is supposed to take up 100% height but currently isn't. Still seeking feedback on this issue. Everything looks per ...

How to use jQuery to convert Latin letters to uppercase in input text

When using the text-transform: Uppercase property, it works fine. However, there is one issue - when I type a lowercase "i", it displays as an uppercase "I" instead of the Latin letter "İ". Is there a way to achieve this using jQuery or another method? ...

How to handle multiple formData input in NestJS controller

How can I create a controller in Nest.js that accepts two form-data inputs? Here is my Angular service code: public importSchema(file: File, importConfig: PreviewImportConfig): Observable<HttpEvent<SchemaParseResponse>> { const formData = ...

JavaScript variables remain undefined outside of the AJAX scope

Currently, I am developing a straightforward script that will allow a specific block of code to execute repeatedly in a loop. var num_rows_php; var num_rows_sessions_php; var num_rows_session_php_teste; $.ajax({ url: 'verify_num_row ...

CSS is not referred to as animation

Every time we hit a key, the dinosaur receives a jump class that should activate an animation. Unfortunately, the animation does not play. animation not functioning <!DOCTYPE html> <html lang="en"> <head> <meta c ...

The Correct Way to Implement Google ReCaptcha

I've developed a PHP contact form that performs validation using AJAX/JSON on the server side. The errors are then passed to Javascript for display and adjustments to the HTML/CSS. My challenge now is to integrate Google ReCaptcha with AJAX validatio ...

Exploring the wonders of Angularjs and the dynamic capabilities of streaming data

Using AngularJS's $http to request streaming data like this: $http({ method: 'POST', url: url, data: JSON.stringify(data), headers: config }).success(function(responseData) { console.log(responseData); }).error(funct ...