skip to Main Content

I am an ASP.NET dev and I want to explore nodejs/express. In ASP.NET you can control raw html from the backend. I want to have a button click toggle the visibility of a div. I know you can do this on the frontend but is there anyways to do this on server side?

This is my code so far

const e = require('express');
var express = require('express');
const path = require('path');
var date;
//var http = require('http');
//var proxiedHttp = require('findhit-proxywrap').proxy(https);
var app = express();
var filePath = '';

app.get('/', function (req, res) {
// send records as a response
console.log(req);
filePath = path.resolve(__dirname, 'index.html');
res.sendFile(filePath);
});

2

Answers


  1. You can achieve the server-side control of a div’s visibility in Node.js and Express by using a templating engine like EJS and defining an endpoint to handle the toggle action.

    1. Install EJS
    npm install ejs
    
    1. Setup EJS in your app
    app.set('view engine', 'ejs');
    app.set('views', path.join(__dirname, 'views'));
    
    1. Create a folder named views (this is proper convention when using ejs). Inside it, create a file called index.ejs. An example of it looks something like this:
    <!DOCTYPE html>
    <html>
    <head>
        <title>Toggle Div</title>
    </head>
    <body>
        <button onclick="window.location.href='/toggle'">Toggle Div</button>
        <div style="display: <%= visibility %>;">
            This is a toggled div.
        </div>
    </body>
    </html>
    

    You can normally just use a variable to control visibility, and send a response based on this variable’s value. However, assuming you want to manage this per-client, you’ll want to use a piece of middleware called express-session, which helps you individualize your users.

    1. Install express session with npm install express-session
    2. Configure
    const session = require('express-session');
    
    app.use(session({
      secret: 'secret-key',
      resave: false,
      saveUninitialized: true
    }));
    
    1. Modify the endpoints to use it
    app.get('/', function (req, res) {
      if (req.session.visibility === undefined) {
        req.session.visibility = 'block';
      }
      res.render('index', { visibility: req.session.visibility });
    });
    
    app.get('/toggle', function (req, res) {
      req.session.visibility = req.session.visibility === 'block' ? 'none' : 'block';
      res.redirect('/');
    });
    

    The visibility of the div is stored in the session, so it’s unique to each client. If one client toggles the div, it won’t affect other clients.

    Sidenote: Writing this post has made me reflect upon the javascript everywhere paradigm.

    Login or Signup to reply.
  2. Switching visibility of a div based on a server-side button click can be a bit different in Node.js/Express compared to ASP.NET, as Node.js is more geared towards handling dynamic interactions on the client side. However, you can achieve a similar effect by mixing server and client-side scripting.

    Here’s a high-level approach using your Express app:

    1. Render Initial State: When the user first loads the page, you can render the HTML with the desired initial visibility state of the div.

    2. Client-Side Interaction: On the client side, use JavaScript (front-end) to handle the button click and toggle the div’s visibility. This keeps the user experience smooth and responsive.

    3. Server Communication: If you need to perform some server-side logic when the button is clicked, you can make an AJAX request to your Express server. This request can trigger server-side actions and send back data if needed.

    So, while the actual visibility toggling happens on the client side, you can still interact with the server through AJAX to trigger server-side actions when necessary.

    Feel free to mix in templating engines like EJS or Pug to make rendering dynamic content in Express even smoother.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search