Home > OS >  How to display image in buttons in HTML
How to display image in buttons in HTML

Time:05-06

Hi I am currently developing a local web server to control things in my car with a RPi 4. I am using nodejs npm express ejs and rpi-gpio libraries.

I want to use the pgio to power relays to control things like lights, led bar, heater, ect so I created buttons but I would like to use images as buttons instead of text and when I try to change the src the IDE CAN find the image and show it to me but when I check on the browser it cant find it

If you also have suggestion to simplify my code I am all ears

The paths looks like this

/Projects/dbDash/package.json
/Projects/dbDash/server.js
/Projects/dbDash/public/200x200/theImage.png
/Projects/dbDash/views/index.ejs

server.js

const express = require('express')
const app = express()
var path = require('path');
var gpio = require('rpi-gpio');

app.set('view engine', 'ejs')
app.use(express.static(path.join(__dirname, 'public')));
console.log(path.join(__dirname, 'public'));
app.get('/', function(req, res){
    res.render('index',{status:"Press Button To change Status of Relay."});
});
app.listen(3000, function () {
    console.log('Server Started on Port: 3000!')
})
app.post('/relay1/change', function(req, res){
    gpio.read(7, function(err, theValue) {
        if (err) throw err;
        gpio.write(7, !theValue)
        console.log("Written "   (!theValue?"true":"false")   " to pin 7");
        return res.render('index', {status: (!theValue?"ON":"OFF")});
    });
})

index.ejs

<div >
    <form action="/relay1/change" method="post">
        <button type="submit" ><img src="../public/200x200/hazard.png" height="200" width="200"/></button>
        <button type="submit" formmethod="post" formaction="/relay2/change" ><img src="../public/200x200/hazard.png" height="200" width="200"/></button>
        <button type="submit" formmethod="post" formaction="/relay3/change" ><img src="../public/200x200/hazard.png" height="200" width="200"/></button>
    </form>
    <form action="/relay4/change" method="post">
        <button type="submit" ><img src="../public/200x200/hazard.png" height="200" width="200"/></button>
    </form>
    <a>Relay Status: <%=status %></a>
</div>

Code Inspector

GET http://localhost:3000/public/200x200/hazard.png 404 (Not Found)

CodePudding user response:

If you're really needing a button just put the image inside the button... If you just do it the way Dr. Bright says that works fine too.

CodePudding user response:

all I need to do is to add this line in server.js

app.use('/public', express.static(process.cwd() '/public'))

thanks to @YasirPoongadan comment then all the buttons show a picture

  • Related