Utilizing jQuery Methods within Node.js

Recently delved into the world of node.js and created multiple pages (such as login, signup, blog, etc).

If I desire an effect in which: 1. Hovering over the "News" button triggers a slider to appear downwards,

  1. To make adjustments to an image within an ejs tag (e.g. <% blog.image %>) without utilizing css.

  2. To implement functionality when the user clicks a button (or any other event).

  3. Currently in my project, clicking on "Login" redirects the user to the "/login" page. I researched "popup login form" tutorials, most of which are for jQuery.

    When using jQuery, I encountered an error: "jQuery requires a window", so I switched from jsdom to cheerio (as recommended by many users). Upon browsing the documentation, I struggled to locate a "click" event method. How can I achieve the tasks mentioned above?

Note: I am not seeking specific code for the aforementioned tasks. I have previously accomplished these tasks in front-end development using jQuery. My inquiry is primarily focused on getting familiar with jQuery in node.js.

Answer №1

Utilizing Node.js as a web server allows it to solely focus on fulfilling your requests, whether it's serving pages or static assets like images, fonts, CSS, and JavaScript files.

For instance, when a user needs to log in, you can set up the index page with a "login" link that directs them to a /login route:

app.get('/', function(req, res){
  res.render('index', { title: 'home' });
});

In the index.ejs file:

<!DOCTYPE html>
<head>
  <title><%= title %></title>
</head>
<html>
  <body>
    <a class="btn" href="/login">LOGIN</a>
  </body>
</html>

Upon requesting http://yourdoamin.com/, Node will serve this index page. However, without any styling or scripting, it lacks interactivity. To address this, configure Node to also serve jQuery along with the index page:

app.use(express.static(__dirname + '/public'));

Create a public folder containing styles and scripts:

/public
  /css
    bootstrap.css
    myStyles.css
  /js
    jQuery.js
    bootstrap.js
    myScripts.js
  /images
  /fonts

Include these styles and scripts in your index.ejs:

<!DOCTYPE html>
<head>
  <title><%= title %></title>
  <link rel="stylesheet" href="/css/bootstap.css">
  <link rel="stylesheet" href="/css/myStyles.css">
</head>
<html>
  <body>
    <a class="btn" href="/login">LOGIN</a>
    <!-- scripts -->
    <script src="/js/jQuery.js"></script>
    <script src="/js/myScripts.js"></script>
  </body>
</html>

Now, by accessing http://yourdoamin.com/, Node will also provide jQuery to the client-side due to its capability of serving static assets. (Alternatively, a CDN can be used for jQuery instead of a static file.)

With jQuery available on the client-side, actions like clicking "login" can be enhanced - preventing the default behavior and displaying a login form popup (utilizing tools like Bootstrap modals):

In myScripts.js file:

$('.btn').click(function(event) {
  event.preventDefault();
  var modalTemplate = $('#modalTemplate').html();
  $('#modal').html(modalTemplate);
  $('#modal').modal('show');
});

In index.ejs:

<!DOCTYPE html>
<head>
  <title><%= title %></title>
  <link rel="stylesheet" href="/css/bootstap.css">
  <link rel="stylesheet" href="/css/myStyles.css">
</head>
<html>
  <body>
    <div id="#modal" class="modal fade"></div>
    <a class="btn" href="/login">LOGIN</a>

    <!-- scripts -->
    <script src="/js/jQuery.js"></script>
    <script src="/js/bootstrap.js"></script>
    <script src="/js/myScripts.js"></script>

    <!-- client-side templates -->
    <script type="text/template" id="modalTemplate">
      <div class="modal-dialog">
        .
        <!-- refer to Bootstrap documentation -->
        .
      </div>
    </script>
  </body>
</html>

This process embodies the concept of Progressive enhancement. Clicking "login" initially redirects to the login page, but users with modern browsers (JavaScript enabled) are presented with a modal login form instead.

While manual client-side development is effective, frameworks like Angular, Ember, as well as tools such as Backbone, React, etc., offer more structured solutions for extensive projects.

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

Adding the output of a UNIX command to a div container

I am currently working on creating a UNIX web-based terminal for educational purposes. My progress so far includes setting up a text box and displaying the output, similar to this: <?php $output = shell_exec('ls'); echo "<pre>$output< ...

Error 56 EROFS encountered when trying to save a file in Node.js filesystem every 2 seconds

I've set up a node.js environment on my raspbian system and I'm attempting to save/update a file every 2/3 seconds using the code below: var saveFileSaving = false; function loop() { mainLoop = setTimeout(function() { // update data ...

Trigger a Jquery sound when an HTML result is found and displayed

I am using a Jqgrid to display a table. Within the "return" column, along with other data, there is a span element like the following: <span class="return" id="ret0>4.25%</span> My webpage contains multiple instances of these spans: < ...

Difficulty encountered when deploying cloud function related to processing a stripe payment intent

I've been troubleshooting this code and trying to deploy it on Firebase, but I keep running into a CORS policy error: "Access to fetch at ... from origin ... has been blocked by CORS policy." Despite following Google's documentation on addressin ...

Searching for elements using jQuery's "attribute-based" selector

Check out this straightforward example on jsfiddle: HTML: <input type="text"/> <input type="text" value="aaa"/> JS: $("input:first").val("aaa"); alert($("input[value='aaa']").length);​ Have you ever wondered why Chrome and IE g ...

Using Jquery toggleClass on a specific icon without impacting the other icons that share the same class

I am currently working on a project where I have multiple divs that each contain an SVG as a background image, specifically for audio player buttons. My goal is to toggle the class of the clicked element without affecting the others. However, I am struggli ...

What techniques can I use to adjust the size of an image through zooming in and out?

In my custom gallery component, the crucial code section looks like this: <Gallery> <Header> <img src={galleryIcon} alt='Galley icon' /> <h1>My Gallery</h1> </Header> ...

Is the Triple DES encryption decryption failing on NodeJS?

let cardDetails = "<Card><CVV></CVV><CardNumber></CardNumber><ExpMonth></ExpMonth><ExpYear></ExpYear><Member></Member></Card>" function generateKeyPair(passphrase){ let iv = crypt ...

What is the process for creating a sub-menu for a dropdown menu item in Bootstrap 5?

https://i.sstatic.net/o4FLn.pngthis is my code which i have created this navigation bar with bootstrap and all of its drop downs but i want to add another drop down to the services drop down section inside of webdevelopment but it can't any easy solut ...

Determine the width of two inline input fields

Showing two inputs side by side: +------------+ +--------------------------+ | ID='inputA'| | ID='inputB' | +------------+ +--------------------------+ +------------------------------------------+ A ...

What is the best way to merge several fetchMore functions within Apollo?

Can Apollo run multiple fetchMores simultaneously? I have a complex hook that executes two queries and combines their results into a single array. This is how it looks: export const useDashboardState = (collection: string) => { // Getting parameters ...

How can images be displayed from an array of post data using a jQuery AJAX request in a Laravel application?

Utilizing an ajax request, I am retrieving post data from a table that contains numerous images and video files. My goal is to retrieve the post model data along with multiple images and videos. However, I am encountering difficulties in displaying this da ...

Webpack error: Unable to locate serverless lambda module

I have been utilizing AWS lambda functions and successfully configured Webpack and Babel to work with ES6 or later JavaScript versions. Additionally, I have set up lambda layers for commonly used Node.js modules. Here is the code snippet from my serverless ...

Can you explain the process for setting the css property text-fill-color in IE and Mozilla browsers, similar to how I set -webkit-text-fill-color for Webkit?

The color displays correctly in Chrome, but how can I make it work in both IE and FF? CSS #Grid td.note div.has-note i { -webkit-text-fill-color: #b4efa8; } ...

Exploring ways to retrieve nested JSON object data in MongoDB using node.js

There's a JSON object stored in MongoDB I'm struggling to figure out how to retrieve Products by ID from the Menu. ...

Express - What could be causing the timeout in my array with a trailing comma?

When working with Express, I have set up a router.post endpoint that is designed to accept an object with a specific structure. The format of the object it accepts is as follows: [ { "tableName": "patients", "tableColumns": [ ...

utilizing jQuery's each method to extract data from a form and then proceeding to transmit it as an asynchronous ajax

As a developer, my goal is to write code that is concise yet meaningful. Currently, I am working on an edit profile form with around 10 text boxes and 2 radio buttons. While it's easy to retrieve values from a simple login form using jQuery like thi ...

What is preventing the mat-slide-toggle from being moved inside the form tags?

I've got a functioning slide toggle that works perfectly, except when I try to move it next to the form, it stops working. When placed within the form tag, the toggle fails to change on click and remains in a false state. I've checked out other ...

The jQuery focus event appears to be malfunctioning

I am attempting to utilize the jQuery focus event to handle the following situation: There are three search criteria options: Post code, city, radius. The user can only select one option, indicated by a radio button. The requirement is that when a user c ...

Passing a null value to a SQL field using JavaScript

I am facing an issue where sending null from AngularJS/JavaScript to my C# controller does not actually set the field as null. How can I properly set a field as null from JavaScript? $scope.formData.currentTempDocument = null return $http({ method: ...