skip to Main Content

I have to buttons, each with an onclick function but I want to merge them into 1.

Button 1: Show a message that things are ok

<button type="button" onclick="UIkit.notification({message: 'This is an alert'})">Click me</button>

Button 2: Add a product to cart (WooCommerce)

<a href="javascript:void(0);" onclick="window.location.href='https://chatsales.nl/pakketten/doe-het-zelf?add-to-cart=420'">Click me</a>

How can I merge those 2 onlick actions into 1 single button click?

Many tnx.

PS. This doesn’t seem to work (product gets added but message is not shown):

<script>
    function action1(){
        UIkit.notification({message: 'Notification message'});
    }
     
    function action2(){
        window.location.href='https://chatsales.nl/pakketten/doe-het-zelf?add-to-cart=420';
    }
</script>
    
<button type="button" onclick="action1();action2();">Click me</button>

3

Answers


  1. You could just create a new function where you execute both actions. Then pass this new function to your button.

    <script>
        function action1(){
            UIkit.notification({message: 'Notification message'});
        }
         
        function action2(){
            window.location.href='https://chatsales.nl/pakketten/doe-het-zelf?add-to-cart=420';
        }
         
        function doActions(){
            action1();
            action2();
        }
    </script>
        
    <button type="button" onclick="doActions();">Click me</button>
    
    Login or Signup to reply.
  2. You can’t assign more than one handler to .onclick, but you can do it with .addEventListener(event, handler) like this:

    const button = document.querySelector('button');
    const link = document.querySelector('a');
    
    function action1(){
      UIkit.notification({message: 'Notification message'});
    }
     
    function action2(){
       window.location.href='https://chatsales.nl/pakketten/doe-het-zelf?add-to-cart=420';
    }
    
    button.addEventListeneer('click', action1);
    button.addEventListeneer('click', action2);
    link.addEventListeneer('click', action1);
    link.addEventListeneer('click', action2);
    
    Login or Signup to reply.
  3. You can do the same with one click only like

    async function actions(){
        await UIkit.notification({message: 'Notification message'});
        window.location.href='https://chatsales.nl/pakketten/doe-het-zelf?add-to-cart=420';
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search