Sammy cannot find element? JS

244 Views Asked by At

I am trying to use Sammy for my SPA, but i cannot handle this error:

[Sun Mar 29 2020 17:37:19 GMT+0300 (Eastern European Summer Time)] #main 404 Not Found get /  Error: 404 Not Found get / 
    at Sammy.Application.error (sammy-latest.min.js:5)
    at Sammy.Application.notFound (sammy-latest.min.js:5)
    at Sammy.Application.runRoute (sammy-latest.min.js:5)
    at Sammy.Application._checkLocation (sammy-latest.min.js:5)
    at Sammy.Application.run (sammy-latest.min.js:5)
    at app.js:23
    at app.js:24 

Seems like the app doesn't find the element i the HTML file but it is there. Here is my JS code and what I have imported in the index.html:

(()=>{
    const app = Sammy('#main', function(){
        console.log('Hello');
    })
    app.run('/#');
})()

HTML:

    <script src="./node_modules/jquery/dist/jquery.min.js"></script>
    <script src="./node_modules/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="./node_modules/handlebars/dist/handlebars.min.js"></script>
    <script src="./node_modules/sammy/lib/min/sammy-latest.min.js"></script>
    <script src="./node_modules/sammy/lib/plugins/sammy.handlebars.js"></script>

(I have div with id= 'main' which i need to use)

Should I make some other configuration or else?

1

There are 1 best solutions below

0
Dony On

As @Dominique said in comment, you should be running the app with app.run('#/') instead of app.run('/#').

Also, you are not using SammyJS properly. If you want to use "basic" routes, you could use GET method :

const app = Sammy('#main', function(){
  // Here you should create routes, and not write code

  // Example : Home page : your.site/page.html
  this.get('#/', function() {
    console.log("Welcome Home");
  });   

  // Exemple : your.site/page.html#/sayhello
  this.get('#/sayhello', function() {
    console.log("Hello");
  });   
})

You can use the URL to use parameters, for exemple, if you want to display in console what you write in the URL :

var app = Sammy('#main', function() {

  // msg is a variable, where its value comes from the url
  this.get('#/display/:msg',function(c) {
    console.log(c.params.msg);
  });

}

Then if you go to your.site/page.html#/display/I_love_donuts ,I_love_donuts will be printed in console.

When I started learning SammyJS, I found this very helpful crash course : https://www.youtube.com/watch?v=QBKm444gO0U . I suggest you to watch it if you are not comfortable with SammyJS yet.

I hope it helped !