juanma
juanma

Reputation: 85

Is it arriving the javascript later than the html?

I'm trying to change the size of a pop-up and give it the same width than the screen, sent from an iframe.

var screen_width = parent.screen.width;

Then I got the html:

<a href="#" onClick="window.open('https://www.google.com','popup', 'width='"+screen_width+"',height=400px')">

I've tryed all possible convinations with the ' " or whatever I know, but I think it should work lie this. Sorry if it's obvious, my coding skills are not so developed, but I think, it's possible, html it's loading before javascript?

P.D.: One more thing, I want to use a variable, because I want to change a bit the real size of the screen.

Upvotes: 0

Views: 40

Answers (2)

user13286
user13286

Reputation: 3075

As mentioned in the comments, you can do this without setting a variable first:

<a href="#" onClick="window.open('https://www.google.com','popup','width=document.documentElement.clientWidth,height=400')">Click Me</a>

Upvotes: 0

Brad
Brad

Reputation: 163448

One problem you might be having is that in your window.open() options, you shouldn't specify px... just put the number for your height.

In any case, here's a better implementation of what you're trying to do. In your HTML:

<a href="http://example.com" target="_blank" data-fullpopup>Click me!</a>

This way, your link will work, and will even open in a new tab/window if your JavaScript doesn't run for some reason. This is a good fallback. The key here is the data-fullpopup attribute, which we'll look for in your JavaScript:

document.addEventListener('DOMContentLoaded', (e) => {
  document.querySelector('body').addEventListener('click', (e) => {
    if (!e.target.matches('a[data-fullpopup]')) {
      return;
    }
    window.open(e.target.href, 'popup', 'width=' + window.screen.width + ',height=400');
    e.preventDefault();
  });
});

Basically, we wait for the document to fully load so that we can attach a click handler to the body element. (Note: If you're only doing this for a couple links, it's better to attach the click handler directly to them. I'm attaching it to body here, assuming that you'll have a lot of these sorts of links... it's more efficient to have one click handler in those cases. Remember though that then this click handler has to run for every click for any element on the page. Choose your tradeoff for your use case.)

Once the link is clicked, we confirm that it's a link with our data-fullpopup attribute. If it is, we treat it like a full-width popup. We get the target (the element) href on the fly, as well as the current screen width. Finally, we prevent the default action so that it also doesn't navigate to the page on its own.

https://jsfiddle.net/L5p0xk98/3/

Upvotes: 1

Related Questions