Skip to main content

How to access AlpineJS Data variable outside scope

Accessing a AlpineJS data in a vanilla JavaScript function out of the AlpineJS component

Published 1 min readMarkdown

This is actually revealing a one-liner solution because Rahul Rajput of rajputrahul.com has already posted a good article and example of how to access a AlpineJS variable outside of its scope at https://www.rajputrahul.com/access-alpinejs-variable-outside-scope/ - but this solution is valid for AlpineJS 2.x only - in version 3.x there is a change in the way its accessed.

In AlpineJS 3.x (while adding https://unpkg.com/alpinejs@3.13.3/dist/cdn.min.js in the script tag to load AlpineJS) :

document.getElementById('modalBox')._x_dataStack[0].open = false;

Full Source Code :

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>How to access AlpineJS Data variable outside scope</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://unpkg.com/alpinejs@3.13.3/dist/cdn.min.js" defer></script>
</head>
<body>
    <h1 class="text-2xl">Example one</h1>
    <div x-data="{open: false}" @keydown.escape="open=false" x-clock>
        <div class="px-8 py-8 align-center">
            <button @click="open=!open" class="px-3 py-1 border shadow-md bg-indigo-500 text-white">Toggle button</button>
            <div x-show="open" id="modal">
                This is modal text.  
                <br>
                <button @click="open=false" class="px-3 py-1 border shadow-md bg-red-500 text-white">Close Me</button>
            </div>
        </div>
    </div>
    <h1 class="text-2xl">Example two</h1>
    <div id="modalBox" x-data="{open: false}" @keydown.escape="open=false" x-clock>
        <div class="px-8 py-8 align-center">
            <button @click="open=!open" class="px-3 py-1 border shadow-md bg-indigo-500 text-white">Toggle button</button>

            <div x-show="open" id="modal">
                This is modal text.  
                <br>
                <button @click="open=false" class="px-3 py-1 border shadow-md bg-red-500 text-white">Close Me</button>
            </div>
        </div>
    </div>
    <button onclick="hideBox()" class="px-3 py-1 border shadow-md bg-red-500 text-white">Toggle button (Outside Scope)</button>
    <script>
        window.hideBox = function(){
            // document.getElementById('modalBox').__x.$data.open = false;
            document.getElementById('modalBox')._x_dataStack[0].open = false;
        }
    </script>
</body>
</html>

About the author

  • I am a web developer from Navi Mumbai. Mainly dealt with LAMP stack, now into Django and getting into Laravel and Cloud. Founder of nerul.in and gaali.in

No comments yet. Be the first to comment.