Tips for sharing a variable with an external JavaScript file in ASP.NET

Utilizing the variables from default.aspx.cs within the script of the default.aspx file has been achieved successfully with the following code:

public partial class default: System.Web.UI.Page
{
    public string _file = string.Empty;
    public string _img = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        _file = "~/videos/myVideo.mp4";
        _img = "~/images/myImg.png";
    }
} 

The code in the default.aspx file:

<html>
  <body>
    <div id="dv_video"></div>
  </body>
</html>

<!-- jw Script -->
<script src="../jwplayer/jwplayer.js"></script>
<script type="text/javascript">
    jwplayer("dv_video").setup({
        file: '<%= _file %>',
        image: '<%= _img %>',
        height: 500,
        width: 850
    });
    </script>
<!-- jw Script -->

To move the script code to an external JavaScript file extras.js, the challenge is how to access the _file and _img variables in that JavaScript file. The code should look like:

jwplayer("dv_video").setup({
    file: '<%= _file %>',
    image: '<%= _img %>',
    height: 500,
    width: 850
});

Edited

The code used to pass parameters to the javascript file extras.js:

<script type="text/javascript" src="<%= Page.ResolveClientUrl("~/jwplayer/extras.js") %>">
    _image: '<%= _img %>';
    _file320: '<%= _file320 %>';
    _file480: '<%= _file480 %>';
</script>

The code to utilize the parameters in the js file:

jwplayer("dv_video").setup({
    image: window._image,
    sources: [{
        file: window._file480,
        label: "480p HD",
        "default": "false"
    },
    {
        file: window._file320,
        label: "360p SD",
        "default": "true"
    }],
    height: 500,
    width: 850
});

Answer №1

If you're looking to accomplish this task, there are a few different options you can explore. One approach is to establish global JavaScript variables in the following manner:

<script type="text/javascript">
_file = '<% _file %>';
_image = '<% _image %>';
</script>

Once these variables are defined, you can access them in your external JavaScript file like so:

var file = window._file;
var image = window._image;

Alternatively, you can include these variables as data values within your HTML structure. Here's an example of how you can incorporate them:

<html>
  <body>
    <div id="dv_video" data-file="<% _file %>" data-image="<% _image %>"></div>
  </body>
</html>

Subsequently, you can retrieve these data values in your JavaScript code using the following method:

var image = $('#dv_video').data('image');
var file = $('#dv_video').data('file');

Answer №2

One minor adjustment needed. Swap out ':' with '=' when assigning values to the variables, as shown in the example below:

<script type="text/javascript">
 _file = '<% _file %>';
 _image = '<% _image %>';
</script>

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

Getting the Featured Image from a Post Link in Wordpress: A Step-by-Step Guide

For my Wordpress project, I have a group of links leading to inner pages, each with their own featured image. These links are created using the menu feature in Wordpress. My goal is to allow users to click on these links and have the featured image from t ...

Deciphering the Cause of mapStateToPropsCall in Redux and React

When handling an unsuccessful http call resulting in an error message being displayed, I encounter subsequent state changes triggering multiple render calls. Is there a technique to identify the cause of these state changes and mapStateToProps calls? Alter ...

I'm having trouble with getting my Bootstrap CSS and JS links to function properly

The paths for the Bootstrap CSS and JS files have been included in the code, but unfortunately, they are not working. Instead, I am getting the following errors in the console: GET http://127.0.0.1:5000/[https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist ...

What is the reason behind having to restart the npm server each time?

When first learning Reactjs with VSCode, there was no need to restart the server after making modifications. However, now I find that I must restart the server every time I make a change in order for those changes to be applied. ...

jQuery - Error: Unexpected token SyntaxError

I'm new to jQuery and facing a challenge with an AJAX request. I have a server on my local network running a Python service. When I make a request to the server through the browser using the URL: http://192.168.0.109:5000/api/environment?seconds=10 ...

Implementing an Asynchronous Limited Queue in JavaScript/TypeScript with async/await

Trying to grasp the concept of async/await, I am faced with the following code snippet: class AsyncQueue<T> { queue = Array<T>() maxSize = 1 async enqueue(x: T) { if (this.queue.length > this.maxSize) { // B ...

Updated Multer version causing issues with uploading image files

After using multer middleware to upload an image, I encountered an issue where the file image was showing up as undefined. This meant that I couldn't retrieve the name or file extension of the uploaded file. I'm not sure if this is an error with ...

Implementing html5mode in Express.js and Angular.js for cleaner URLs

I've been working on resolving the issue of avoiding # in my Angular app with an ExpressJS server-side setup. I found a solution to enable html5mode and it worked well. However, whenever there is another 'get' request to fetch data from a di ...

Tips on running methods consecutively within ngOnInit in Angular

I'm currently working on an ngoninit function that contains four methods. Two of these methods are responsible for retrieving data from the API, while the other two are intended to load this data when the page loads. ngOnInit(){ getname(); getsubjects ...

Leveraging the power of JavaScript to retrieve data from BigQuery

Having just started my journey with JavaScript and Google BigQuery, I am seeking help due to my lack of experience in these areas. My goal is to create a javascript code that can fetch data from one of the public databases on BigQuery. I came across a solu ...

When I send data using axios, I receive the response in the config object instead of the data

Currently, my web app is being developed using NextJS NodeJS and Express. I have set up two servers running on localhost: one on port 3000 for Next and the other on port 9000 for Express. In the app, there is a form with two input fields where users can e ...

How to determine the length of a JavaScript object

Would like help determining the length of the report_data(object) key using the provided code, but it seems to result in a value of 3. a={report_freq: "daily", report_item_num: 2, report_num: 39, report_data: "{}"} Object {report_freq: "daily", report_ite ...

Filtering with multiple attributes in Angular using GroupBy

I have a set of JSON data structured like this: [ { "id": 1, "address": "MG Road", "country": INDIA, "state": AP, "city": VIJ }, { "id": 2, "address": "Miyapur", "country": INDIA, ...

Express.js code is experiencing difficulties with autocomplete functionalities

jQuery autocomplete code example [Express JS code for retrieving data][2\ Example of fetching data in Express JS ...

Struggling with utilizing data encoded by PHP into JSON format when working with JavaScript to showcase graphs using the chart.js library

My goal is to showcase a graph using the chart.js JavaScript library. I am retrieving data from a database in PHP and passing it to JavaScript using the json_encode() method to convert it into a JavaScript variable. The data consists of two fields from a & ...

Do not allow navigation to another page until the form has been submitted

As part of my project, I have implemented a feature where new users are required to change their password upon logging into their account for the first time. For new users, the Change Password screen is displayed immediately after login. The menu options ...

JavaScript - Removing Content from an Element

I have a coding script that adds an image preview of uploaded images. The issue I am facing is that the previous image does not clear when the form is filled out again. The id of the div where thumbnail images are being displayed is "thumbnail". Can someo ...

Embedding HTML Tags within an array element

The task at hand involves adding an HTML element from Array Value to the Document Object Model template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: &a ...

Disallow caching when a certain URL parameter is present

When using cache in my .aspx page (ASP.NET 4), I have it set up like this: <%@ OutputCache Duration="100000" VaryByParam="CategoryID" %> Everything works perfectly, but when the page URL contains traceid, I want to avoid using any cache. Is there ...

Transferring an ES6 class from Node.js to a browser environment

I've been exploring ways to bundle a super basic ES6-style class object for the browser. Here's an example: class Bar { constructor(){ this.title = "Bar"; } } module.exports = Bar; While I can easily utilize this in my node projec ...