-1

i am creating a website at school that has a news article and i want to use javascript to create a button which will bring you to the actual news article from the homepage of my website. I have tried doing:

<script> 
var button = 'button'
window.location=('http://www.example.com');
}
</script>

but this hasn't worked for me, i'm not suer if my html is wrong or my css.

  • Welcome to StackOverflow! Neither your HTML nor your CSS is wrong... though your JavaScript certainly is. `window.location()` is used incorrectly, and would redirect immediately. You'll want to attach a click event to the button with `addEventListener()`, and then insert it to the DOM with `.createElement`. – Obsidian Age Mar 28 '18 at 21:40
  • BTW, `var button = 'button'` doesn't create a button if you think it does. You need [`document.createElement`](https://developer.mozilla.org/en-US/docs/Web/API/Document/createElement) for that. – Vasan Mar 28 '18 at 21:44
  • 1
    Possible duplicate of [Creating Dynamic button with click event in JavaScript](https://stackoverflow.com/questions/7707074/creating-dynamic-button-with-click-event-in-javascript) – Obsidian Age Mar 28 '18 at 21:44

2 Answers2

1

The easiest way to create a link on a website is by using an anchor element in your html, like so:

<a href='http://yourwebsiteurlhere.com'>Go to site</a>

If you really want to accomplish this using javascript, you could do so like this:

<a onclick="sendToWebsite()">Go to site</a>
<script>
    function sendToWebsite() {
        window.location.href='https://www.thelinkyouwantogoto.com'
    }
</script>

Hope that helps.

Niall McQuay
  • 326
  • 3
  • 10
0

You can wrap a around button.

<a href="javascript:console.log(1);"><button>x</button></a>
yajiv
  • 2,901
  • 2
  • 15
  • 25