TimB
TimB

Reputation: 1000

How to access location attribute of window object?

I have problems with accessing the location attribute of the window object, which I need to redirect the user to another page via JavaScript/jQuery. I know you normally should use an .htaccess file to do this, but I'm actually writing an nw.js application, so I have no server.

Here is an example source code:

<!DOCTYPE html>
<html>
<head>
  <title>Test</title>
  <script src="http://code.jquery.com/jquery-3.2.1.js">
  </script>
  <script>
  $(function() {
    $("#testbutton").click(function() {
      $("#testbutton).before($(window).attr("location"));
    });
  });
  </script>
</head>
<body>
  <button type="button" id="testbutton">Click me</button>
</body>
</html>

This should, if it worked, get the value of the location attribute and insert it before the button when the button gets clicked.

In reality, it doesn't do anything. I also tried to assign the value of the location attribute to a variable, or write this in plain JavaScript (which I intend to avoid), but neither did change the fact that nothing happens.

Is it possible to access the location attribute of the window object via jquery? And if it's possible, what's my mistake?

I wanted to print the value first before changing it, because I like to develop projects step by step. I know this code is not going to change the location attribute, but I wonder why it's not even getting the value?

Upvotes: 0

Views: 1009

Answers (2)

charlietfl
charlietfl

Reputation: 171669

You don't need jQuery....just access the location.href directly

$(function() {
  $("#testbutton").click(function() {
    $("#testbutton").before(location.href);
  });
});
<script src="//code.jquery.com/jquery-3.2.1.js"></script>
<button type="button" id="testbutton">Click me</button>

Upvotes: 1

mostafa tourad
mostafa tourad

Reputation: 4388

The window Object is a global Object and has many properties that you can read and edit , one of this properties is the location Object which is not a text its an object that holds some information about the current location and urls but you can access the current url location using location.href and then you can insert this text any place you want , look at the example below

$(function() {
    $('#testbutton').click(function() {
        var currentUrl = window.location.href;
        $('#testbutton').before(currentUrl+'<br>');
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <button type="button" id="testbutton">Click me</button>
</body>

Upvotes: 1

Related Questions