Is there a way to simply go to a new webpage in Elm, similar to clicking on a link?
I have a button
that when clicked I want to take the user to another webpage. I know I could make that an a
element and use CSS to style it like a button. However, I'm using elm-mdl
to create material design lite buttons and I'd like to know how to do this regardless.
I've tried creating a GoTo String
Msg
and firing that on the button click with Button.onClick (GoTo "newpage.html")
, but I don't know what to put for the Cmd
. I tried the following:
GoTo url ->
( model, Navigation.newUrl url )
But that only makes the URL in the address bar change, the user doesn't actually go to the new url... I could use a port and write some simple JavaScript code to call window.location.href = 'newpage.html'
, I'm just hoping there's a simple standard Elm way to do this.
What would work for your current situation would be to use a port and force JavaScript to do it for you. This is library agnostic. The reason I would like to suggest doing it this way is that if an <a>
tag is not acceptable and you want a Cmd msg
, then this will give you exactly that.
I will include a basic example that should fairly easily correlate to what you're doing.
You should create a module that accepts ports or convert one of your current ones to use them by creating a module and adding port
to the beginning of the module declaration. You can also just modify an existing module to do this in the same way.
A sample module for this would be
port module OpenWindow exposing (openWindow)
port openWindow : String -> Cmd msg
Now you have your port declaration in your code. You can use it where you want by wrapping it in a function or you can simply call openWindow
from your update function when you import it from the module OpenWindow.
Next you should add your port JavaScript code.
In your index.js
or your <script>
tag where you define the usual
var Elm = require('../Main');
var node = document.getElementById('main');
var app = Elm.Main.embed(node);
or however you do it, simply add
app.ports.openWindow.subscribe(function(newSite) {
window.open(newSite);
});
You would just add this to your original example by code like
GoTo url ->
( model, openWindow "newpage.html" )
Personally, I would not recommend doing this often as this is not really the best way if normally an a [] []
statement would work.
You could more properly probably add an anchor tag to your button and reference it that way.
Note: Additional information about the window.open() function can be found here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With