How To Open New Window In Jquery

In this blog post, we will learn how to open a new window using jQuery. jQuery is a popular and widely-used JavaScript library that simplifies various tasks like DOM manipulation, event handling, and animations, among others.

Opening a New Window Using the window.open() Method

To open a new window in vanilla JavaScript, we can use the window.open() method. This method accepts three parameters: the URL, the window name, and the window features. For example:

window.open("https://www.example.com", "_blank", "width=600, height=400");

This code will open a new window with the specified URL and dimensions. But how can we do this using jQuery? Let’s find out.

Opening a New Window in jQuery

jQuery doesn’t have a specific method for opening a new window. However, since jQuery is a JavaScript library, we can use the same window.open() method in combination with jQuery event handling. The following example demonstrates how to open a new window when a certain button is clicked:




    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>jQuery Open New Window</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>


    <button id="openWindowBtn">Open New Window</button>

    <script>
        $(document).ready(function() {
            $("#openWindowBtn").click(function() {
                window.open("https://www.example.com", "_blank", "width=600, height=400");
            });
        });
    </script>


In this example, we first include the jQuery library using the <script> tag. Then, we create a button with an ID of openWindowBtn. Inside the <script> tag, we use the $(document).ready() function to ensure that the DOM is fully loaded before our jQuery code is executed.

Next, we use the jQuery click() event to attach an event handler function to the button with the ID openWindowBtn. When this button is clicked, the window.open() method is called with the specified URL and dimensions, opening a new window.

Conclusion

Although jQuery doesn’t have a built-in method for opening a new window, we can easily achieve this functionality by combining the window.open() method with jQuery event handling. This allows us to easily open a new window when a specific element, like a button, is clicked.