Support

Account

Home Forums Gutenberg Prevent clicks on anchors

Solving

Prevent clicks on anchors

  • I have built an ACF Block that loads posts in a grid. Each post in the grid is clickable. Working fine except that in the editor you can accidentally activate the links taking you off to the posts while you are trying to edit.

    In order to prevent the clicks, I’ve implemented the following code but I can’t get any jquery to apply, although I can confirm the file is definitely loading in the header. I realise you can load js using register_block_type(), but as I want to prevent clicks on any links on any blocks in the editor, it makes sense to enqueue from functions.php.

    functions.php

    	//* Enqueue Gutenberg styles 
    		wp_enqueue_script( 'testJs', get_bloginfo( 'stylesheet_directory' ) . '/js/test.js', array( 'jquery'));
    	}

    test.js

     jQuery( function($) {
        'use strict';
    
    // Stop links from activating in the editor
    $("a").click(function(event){
        event.preventDefault();
      });
    
    });

    What am I missing .

  • You haven’t shared the action you’re using to enqueue your script, but I’d double check you’re using admin_enqueue_scripts and not wp_enqueue_scripts.

    eg:

    add_action('admin_enqueue_scripts', 'your_function');
    function your_function() {
      wp_enqueue_script( 'testJs', get_bloginfo( 'stylesheet_directory' ) . '/js/test.js', array( 'jquery'));
    }

    I usually achieve this using CSS for ease, but this method will remove hover events too, which you might not want!

    In the custom block CSS file:

    .acf-block-preview .your-block-name {
        pointer-events: none;
    }
  • if Using CSS I would probably use this, or else it’s likely you wont be able to select your block in the backend to edit it at all.

    .acf-block-preview .wp-block-acf-button-block a {
        pointer-events: none;
    }
    
  • Good ideas for the CSS workaround! Nice and clean. But just a note, the above code has an extra space in it. I believe it should be something like:

    .acf-block-preview.wp-block-your-block-name a {
      pointer-events: none;
    }
    
Viewing 4 posts - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.