htmljquerynode.jsnpmelectron

JQuery not working with electron framework


I'm trying to using jquery with electron framework using electron fiddle. However jquery seems not working properly and animation are not executed. The example is the following: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_animation1

main.js

// Modules to control application life and create native browser window

const {app, BrowserWindow} = require('electron')

function createWindow () {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      nodeIntegration: true
    }
  })

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // On OS X it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow()
  }
})

index.html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <title>Hello World!</title>
    <link rel="stylesheet" type="text/css" href="./styles.css">
<script>window.$ = window.jQuery = require('https://code.jquery.com/jquery-3.3.1.slim.min.js');</script>

<script> 
$(document).ready(function(){
  $("button").click(function(){
    $("div").animate({left: '250px'});
  });
});
</script> 

  </head>
  <body>
    
<button>Start Animation</button>

<div style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

<script>
  // You can also require other files to run in this process
  require('./renderer.js')
</script>

  </body>
</html>

Nothing happens once clicked on the button.


Solution

  • Normally you'd install electron via npm install jquery to your node_modules folder and require it inside your renderer.js. So:

    window.$ = window.jQuery = require('jquery');
    

    belongs inside the renderer.js. This way you have it locally and yiu are not depndant on an external CDN anymore.