Separate your export function calls into their own dedicated file

Currently, I have a function defined in my app.js. The goal now is to separate the function calls into a different file.

// Function to add .rellax class and data attribute
function addRellax(selector, value) {
    // Select all elements that match the given selector
    const elements = document.querySelectorAll(selector); // Add .rellax class to selected elements
  
    for (var i = 0; i < elements.length; i++) {
      elements[i].classList.add('rellax');
    } // Control speed
  
  
    for (var i = 0; i < elements.length; i++) {
      elements[i].setAttribute('data-rellax-speed', value);
    }
};

// Applying parallax effect to different elements
// These three lines will be moved to another file
addRellax('.helloWorld__item1', 6);
addRellax('.helloWorld__item2', -2);
addRellax('.helloWorld__item3', 3);

// Initialize Rellax
const rellax = new Rellax('.rellax');

To achieve this, I created a new file named helloWorld.js and attempted the following:

export default
addRellax('.helloWorld__item1', 6);
addRellax('.helloWorld__item2', -2);
addRellax('.helloWorld__item3', 3);

I then replaced the mentioned part in my main app.js with:

// Adding parallax effect to elements
import './05-sections/helloWorld/helloWorld.js';

However, upon testing, I encountered an error:

Uncaught ReferenceError: addRellax is not defined at Object../src/05-sections/helloWorld/helloWorld.js

Answer №1

To ensure the proper execution of functions in helloWorld.js, it is necessary to import app.js into helloWorld.js. Simply importing helloWorld.js into app.js does not automatically execute that js file; instead, it grants access to the code contained within.

What motivates your decision to invoke these functions in a separate js file?

Answer №2

Ensure that if your function resides in the app.js file, you must export it from there:

export default addRellax;

Subsequently, you can easily import it to any other location by using the following syntax:

import addRellax from 'app.js path';

The 'app.js path' should be replaced with the actual path leading to your app.js file.

Answer №3

To utilize the functionality in helloWorld.js, you must import app.js

Make sure to export addRelax from App.js

function addRellax(selector, value) {
    // find elements matching the selector
    const elements = document.querySelectorAll(selector); // apply .rellax class to selected elements
  
    for (var i = 0; i < elements.length; i++) {
      elements[i].classList.add('rellax');
    } // set speed
  
  
    for (var i = 0; i < elements.length; i++) {
      elements[i].setAttribute('data-rellax-speed', value);
    }
  }
;

// Implement parallax on elements
// The following lines will be stored in hellowWorld.js
//addRellax('.helloWorld__item1', 6);
//addRellax('.helloWorld__item2', -2);
//addRellax('.helloWorld__item3', 3);

// Initialization
const rellax = new Rellax('.rellax');
export default addRellax;

test it out in hellowWorls.js

import addRellax from 'App.js' //provide correct app.js file path
// Apply parallax to elements
// These three lines will be moved to a separate file
export const addRellaxItem6 = addRellax('.helloWorld__item1', 6);
export const addRellaxItem2 = addRellax('.helloWorld__item2', -2);
export const addRellaxItem3 = addRellax('.helloWorld__item3', 3);

//alternatively, export as an object 
export default {
   addRellaxItem6,
   addRellaxItem2,
   addRellaxItem3
}

Add the addRelax function in hellowWorld.js or any desired file for easy importing.

If relaxation-related code needs to be used in multiple places, consider creating a relaxation utility file like relaxUtil.js

//relaxUtil.js
export const rellax = new Rellax('.rellax');//can now be imported anywhere
export function addRellax(selector, value){ //useful for various components
//relaxation related code
}
export const addRellaxItem3 = addRellax('.helloWorld__item3', 3);

//alternatively, export as an object 
export default {
   addRellaxItem6,
}

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

Updating variable storage in React components

This is a project built with Next.js and React. Below is the folder structure: components > Navbar.js pages > index.js (/ route)(includes Navbar) > submitCollection.js (/submitCollection)(includes Navbar) The goal is to allow users to inpu ...

What is the best way to define a default value for a v-text-field in Vuetify within a Nuxt.js project?

As a beginner with vuejs and nuxtjs, I have been introduced to vuetify at my workplace. I am currently trying to set the default value of 0 for v-text-field fields in the application, but unfortunately, I cannot seem to find this information in the vueti ...

Unable to access $_SESSION variable when making AJAX request from a different port

After creating a website with PHP on port 80 (index.php) and setting the session variable with the userid upon login, I encountered an issue when clicking on a link that redirected me to port 8080, which is where a JavaScript file containing node.js proces ...

The canvas loadFromJson function fails to implement the font-family property

I have implemented the following code to display Google font and update the canvas: /* on change of font, load the preview and update the canvas */ $('#font').on('change', function () { $('.font_preview').show ...

Place the div absolutely on top of the Flash content

Can a <div /> be absolutely positioned over a Flash banner without including wmode="transparent" in the banner? I am trying to display a lightbox above my ads, but I cannot make changes to the banners since they are provided by a third party. Edit: ...

Steps to Create an HTML Text Box that cannot be clicked

Does anyone know of a way to prevent a text box from being clicked without disabling it or blocking mouse hover events? I can't disable the text box because that would interfere with my jQuery tool tips, and blocking mouse hover events is not an opti ...

Retrieve the current row by clicking the button

I've been struggling to retrieve a specific value from a row displayed on my PHP webpage. My objective is to obtain the current value from a particular cell in the row, but using getElementsByTagName has not been successful as it only returns an HTMLC ...

I'm having some trouble with my jQuery.get() function in the javascript Saturday(), can anyone help me figure out what I'm doing wrong?

Can anyone help me troubleshoot my jQuery.get() method in the saturday() JavaScript function? Here is the code snippet I have been working on. This is what I have in my index.html file: <html> <head> <title>jVectorMap demo</title> ...

Asking for information regarding RESTful API

Could you please assist me in identifying the most suitable technologies for integrating a RESTful API into an HTML and CSS website? The primary objective is to enable the website owner to easily log in and add news entries about their business. Addition ...

Can Vuejs functions be triggered using a jQuery event trigger?

I am currently attempting to trigger a change event within a Vue component. Within the component template, there is a select element. When I try to use jQuery to trigger a change event on this element, the Vue component does not seem to detect it. Here i ...

Tips for setting up an environmental variable in a node.js environment

I am a big fan of node.js, to the point where I want to incorporate it into my bash start up script ~/.bashrc. However, I am unsure of how to properly export variables. As of now, I am using this method: export PS1=`node ~/PS1.js` export PS2=`node ~/PS2. ...

Learn the method for automatically checking a checkbox when a page is loaded in Angular

I have multiple checkboxes on a single page <div class="check-outer"> <label>Place of operation</label> <div class="checkDiv"> <div ng-repeat="place in places"> <div class="checkbox-wrapper"> ...

MVC3 does not support JQuery UI

Just recently, I had all my jquery-ui elements functioning perfectly. However, now it seems that none of the jquery-ui features are working anymore. In my Site.Master page, I have included the following code... <link href="../../Content/Site.css" rel=" ...

Creating a div background that is transparent within a Bootstrap modal

Here is the HTML (Bootstrap) code I have: <div modal="showModal" close="cancel()"> <div class="modal-header text-center"> <h2>Members who shortlisted you </h2> </div> <div class="modal-body"> ...

Rendering in ThreeJS Causes IE11 to Crash

I encountered a peculiar issue with Internet Explorer 11 while working on WebGL programming. Everything was functioning smoothly in all browsers until, out of the blue, IE started crashing when altering the positions of 4 meshes, without pointing to any sp ...

What are the steps for loading JSON data into a select dropdown with the help of AJAX?

I am trying to create a dropdown list of schools using the select tag. Currently, I have hard coded values for the list, but I want to fetch the data from a RESTful service instead. Can someone please provide guidance on how to achieve this? <html& ...

Stop angular schema form's destroyStrategy from deleting any data

After upgrading my Angular app from version 0.8.2 to 0.8.3 of Angular Schema Form (ASF), a significant bug emerged. The application features multi-page forms that utilize prev/next buttons for navigation. A condition is implemented to display only relevan ...

Obtaining the name of the image that has been uploaded using jQuery

//Image upload function $(function() { $(":file").change(function() { if (this.files && this.files[0]) { var reader = new FileReader(); reader.onload = imageIsLoaded; reader.readAsDataURL(this.files[0]); } }); }); function im ...

Building an LED display with three.js

I have a project where I am creating a board with multiple RGB LEDs mounted on it, as shown in the image. https://i.sstatic.net/WtOm4.png To create the LEDs, I used the following code: this.light = new THREE.PointLight(color, intensity, distance, decay) ...

Guidelines for ensuring that a radio button must be chosen prior to submission

I'm struggling with implementing AngularJS validation for a set of questions with radio answer choices. I want to ensure that the user selects an answer before moving on to the next question by clicking "Next". Check out my code below: EDIT: Please k ...