Dynamically populate a JavaScript array

I have a javascript file that is used for a slider, which retrieves image URLs from an array. How can I dynamically add image URLs from the code behind? I need to fetch picture URLs from a database and insert them into the array using asp.net c#. The jQuery code snippet looks like this:

$(function() {
    $('#ds_showcase').showcase({
        linksOn: 'images',
        css: {},
        animation: { autoCycle: true, type: 'horizontal-slider', interval: 4000, stopOnHover:true, speed: 1500, easefunction: 'easeOutBounce'},
        images: [
                  { url: 'Showcase_ds_images/lift-truck.jpg ', description: 'Title 2', link: '', target: '_self' },
                  { url: 'Showcase_ds_images/lifttruck2.jpg', description: 'Title 3', link: '', target: '_self' },
                  { url: 'Showcase_ds_images/lift-truck3.jpg', description: 'Title 4', link: '', target: '_self' },

        ],
        navigator: { position: 'bottom-right', orientation: 'horizontal', autoHide: false, showNumber: false,
            css: { padding: '10px'}, 
            item: { css: { height: '10px', width: '10px', backgroundColor: '#cccccc', borderColor: '#999999'},
                    cssHover: { backgroundColor: '#3399ff'},
                    cssSelected: { backgroundColor: '#3399ff', borderColor: '#3399ff'}
            }
        }

    });
});

Answer №1

If you want to achieve a similar result, you could consider the following approach:

let jsArray = [];
<%for(let item of items){%>
   jsArray.push('<%=item%>');
<%}%>

This piece of code will create JavaScript with predetermined strings obtained from the server. Each client will have JS that looks something like this:

 let jsArray = [];

    jsArray.push('http://example.com/item1.png');
    jsArray.push('http://example.com/item2.png');
    jsArray.push('http://example.com/item3.png');

In your specific scenario, you could use something along these lines:

$(function() {
    let jsArray = [];
    <%for(let item of items){%>
       jsArray.push({url: '<%=item.url%>', description: '<%=item.desc%>', link: '', target:'_self'});
    <%}%>

    $('#showcase').presentation({
        linksOn: 'items',
        css: {},
        animation: { autoCycle: true, type: 'horizontal-slider', interval: 4000, stopOnHover:true, speed: 1500, easefunction: 'easeOutBounce'},
        items: jsArray,
        navigator: { position: 'bottom-right', orientation: 'horizontal', autoHide: false, showNumber: false,
            css: { padding: '10px'}, 
            item: { css: { height: '10px', width: '10px', backgroundColor: '#cccccc', borderColor: '#999999'},
                    cssHover: { backgroundColor: '#3399ff'},
                    cssSelected: { backgroundColor: '#3399ff', borderColor: '#3399ff'}
            }
        }

    });
});

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

Guide on integrating a custom language parser and syntax validation into Monaco editor

I am in need of guidance on how to define a custom language in the Monaco editor. Despite my efforts, I have been unable to locate a reliable source for this documentation. My goal is to create a language with syntax similar to JavaScript, enabling users ...

`Slide align center in the bxslider``

I am attempting to create a slider that is centered on the view. The slide in the center should be positioned at the center of the red line(div). This is my attempt: https://fiddle.jshell.net/4xgpgng1/1/ <style> div.bxslider { margin:0 50%; text-al ...

Is there a way to ensure that my mouseenter function does not run when it is currently in the process of running?

Issue at hand: Currently, I am tackling a problem with the mouseenter function $('.filmstrip').bind('mouseenter',function(){ var isRunning = false; var $elem = $(this), width = $elem.width(), ...

why doesn't the promise return the record after it has been updated

After completing the form, I proceed to send it as an object to the API NodeJS. The following is the execution function: .post('/create/card', function (req, res) { var rb = req.body, obj = { query: { $set ...

Removing solely the selected item, leaving the rest of the elements on the canvas untouched

Just starting out with coding and working on a game for a school project. The idea is to have random circles or "targets" appear on the screen, and the user has to click them. I've been struggling with keeping the "un-clicked" circles on the canvas wh ...

I consistently encounter a "KeyError" when attempting to retrieve specific values by keys from a dictionary array

I am facing an issue with a dictionary I have created using Selenium that consists of list elements with strings defining some attributes. Here is the structure of the dictionary: #The dictionary is structured as follows. {0: {0: ['string1', &apo ...

What is the solution for displaying all table rows in a gridview when the associated textbox is left empty?

The filter function in my gridview is working perfectly when I enter text into the textbox. However, I am facing an issue where no results are displayed in the gridview when the textbox is empty, and I cannot figure out why. QUERY Is there a way to disp ...

Angular 6 provides a regular expression that specifically targets the removal of any characters that are not numbers and enforces the allowance of

I have tried various solutions to restrict input in an Angular material input box, but none seem to be effective for my specific case. I need the input field to only allow numbers and a decimal point. Any other characters should be automatically removed as ...

Acquire an HttpRequest similar to that of Fiddler

Is there a simple method to transform the complete HttpWebRequest into a single string? Just like how Fiddler presents it in the Raw tab of the request pane? Appreciate any guidance you can provide. ...

Creating a Singleton Database in asp.net mvc3 using Code First

Currently, I am utilizing asp.net mvc with code first approach. Upon creating a new controller, I observed that the template includes an overridden dispose method which simply disposes of the db variable at the top of the controller. My idea is to switch ...

Trouble with parsing JSON in NodeJs

I have a JSON file containing the names of people that are stored. Using the Node Manager's filesystem, I read the content from this file and attempt to convert the JSON to a string and then parse it into a JavaScript object. However, after parsing it ...

The array error is looking for a specific class

I'm struggling to understand why this code is not working and it's showing a .class error. Any assistance would be highly appreciated. Thank you! public static int displayPercentageAndGrade(int assignMax, int assignScoreArray, int labMax, int la ...

Inquiries regarding scopes, node.js, and express

I struggle with understanding scopes and similar concepts in various programming languages. Currently, I am working on an express application where I take user input, query an arbitrary API, and display the results in the console. To interact with the REST ...

Issue with ASP.NET Core Controller not properly receiving complete JavaScript array object from Ajax call

When passing a JavaScript Object Array through ajax to the controller, I noticed that if there are more than 11 objects in the array, the controller receives it as null. However, with 11 or fewer objects, the array is received successfully. Here is an exam ...

An ASP.NET MVC project deployed on Azure integrating with clearDB mySQL through SSL authentication

I am utilizing a complimentary subscription on Azure that includes a web application and a small mySQL database from cleardb.com (Dreamspark). ClearDB offers certificate downloads for SSL authentication to the database, and I have successfully connected to ...

Can the asynchronous function be further optimized?

Here is a function that I have: public async Task<string> EagerLoadAllAsync<T>(params Expression<Func<T, object>>[] includeProperties) where T : class { var entities = await _repository.EagerLoadAllAsync(includeProperties); ...

Instructions for submitting three different forms from three separate pages simultaneously

I am facing a challenge where I have 3 forms spread across 3 different pages, with the submit button located on the 3rd page. Is there a way to submit all 3 forms simultaneously by clicking on the submit button? Are there any solutions available in javascr ...

Embrace the power of perpetual movement in an ember concurrency task without hindrance

if (isEmpty(contactData) || isEmpty(get(contactData, 'emails'))) { contactData = yield store.findRecord('contact', contactId); } if (isEmpty(contactData) || isEmpty(get(contactData, 'emails'))) { flashMessages.danger(i18n ...

Utilize Photoshop's Javascript feature to extract every layer within the currently active document

Looking for insights on a Photoshop scripting issue. I have written a solution but it's not producing the correct result. Can anyone provide feedback on what might be wrong with the code? The goal is to retrieve all the layers in a document. Here is ...

Ensure confirmation dialog box pops up multiple times when deleting an item using AJAX

On my website, I have a side menu with multiple navigation items. In the admin section, there is a table where I can manage these items. The issue arises when I delete an item from the table using ajax - it gets deleted from both the table and the side men ...