Explain Codes LogoExplain Codes Logo

Onclick open window and specific size

javascript
popup-blockers
cross-browser-compatibility
responsive-design
Anton ShumikhinbyAnton Shumikhin·Nov 7, 2024
TLDR

Use window.open() within your onclick event to create a new window with a specific size:

<button onclick="window.open('http://example.com', '_blank', 'width=200,height=100')"> Open Window </button>

Remember to adjust width and height to your desired pixel values.

In brief, you create a window.open() function within an onclick event. Modify the width and height parameters to change the popup's size. Enhance your function with additional parameters like scroll bars, menu bars, and resize condition.

Feature-rich custom window

Add more functionality to your popup window:

<button onclick="window.open('http://example.com', '_blank', 'width=350,height=250,scrollbars=yes,menubar=no,resizable=yes')"> Open Custom Window </button>

With these parameters, your window becomes more interactive - contains scroll bars, does not display a menu bar, and is resizable. Don't forget, each feature must be separated by a comma and set in single quotes.

Make it fancy: CSS appeal

Aesthetics draw attention. Let the styles do the action cue:

button { cursor: pointer; /* Play around with the styles: attract, don't distract. */ }

By specifying cursor:pointer, mouse pointer changes, hinting that the button triggers an action. Good design means more interactive elements.

Dealing with the pop-up blockers

Pop-up blockers can be a buzzkill. Handle them graciously:

  • Inform users about enabling pop-ups for your site.
  • Detect pop-up blockers:
var newWindow = window.open('http://example.com', '_blank', 'width=200,height=100'); if (!newWindow) { alert('Please disable your pop-up blocker. Save us both some trouble.'); }

Warn users about pop-up blockers, so they don't miss out on your fantastic content.

Cross-browser compatibility

Different browsers may ruffle your fancy feathers. Ensure window.open() is keyboard-friendly:

  • Use feature detection for browser quirks.
  • Test your code cross-browser.
  • Have fallbacks ready for all platforms.

Below table shows support for window.open() settings across major browsers:

FeatureChromeFirefoxSafariEdgeIE
Fullscreen✔️✔️✔️
Resizable✔️✔️✔️✔️✔️
Scrollbars✔️✔️✔️✔️✔️