Evanss
Evanss

Reputation: 23142

Set parameters of width and height for link that will open in a new window with javascript?

With the following I can open a link in a new window if it has a class of "open-new-window".

  (function () {

    $('.new-window').click(function(){
       window.open(this.href, 'newwindow', 'width=400, height=200'); 
       return false;
     });

  })();

<a class="new-window" href="somesite.com">Link </a>

How can I rewrite this so the width and height of window thats created are passed by parameters in the HTML?

So I was thinking something like this:

 <a class="new-window" data-window-width="400" data-window-height="200" data-name=" href="somesite.com">Link</a>

Note - I will need to have multiple links like this on a page, each with different height and width parameters.

I also need to centre the popup but I think I can do so with this method once I have he window height and width as parameters.
Open new window on center of screen with this javascript?

Upvotes: 0

Views: 1636

Answers (2)

clinton3141
clinton3141

Reputation: 4841

You can use either $(this).data("window-width") or $(this).attr("data-window-width") with jQuery to get at the data attributes. They're not quite equivalent to each other, but unless you're planning in modifying the widths/heights in JavaScript you can consider them to be the same. If you need to modify the values, you should take some time to understand how each is affected by updating the <a>.

(function () {

  $('.new-window').click(function(){
    var window_width = $(this).data("window-width"),
      window_height = $(this).data("window-height"),
      window_name = $(this).data("name");
    window.open(this.href, window_name, 'width=' + window_width + ', height=' + window_height); 
    return false;
  });

})();

Upvotes: 2

jAndy
jAndy

Reputation: 236122

You can access dataset attributes via the Element.prototype.dataset property.

window.open(this.href, 'newwindow', 'width=' + this.dataset.windowWidth + ', height=' + this.dataset.windowHeight + '); 

Note: hyphens are converted into camel case notation for accessing.

Upvotes: 0

Related Questions