Issue #2177Opened July 31, 2019by alikabeer323 reactions

How to create a block with HTML and CSS and javascript content.

Question

Can somebody please show me a code example of how to create a block with javascript and css styles.


    editor.BlockManager.add('a_block', {
      label: 'Sample Block',
      content: 
          `<style>
              .sampleclass{
                padding:10px 15px;
              }
              .sampleclass2{
                opacity:0;
                visibility:hidden;
              }
              .sampleclass:hover > .sampleclass2{
                visibility:visible;
                opacity:1;
              }

              @media (max-width: 768px){
                .sampleclass{
                  width:100%;
                }
              }
          </style>
          <div class="samplecalss">Text<div class="sampleclass2"><div><a>A Link</a></div></div>
              <script>
                 console.log('hello world');
              </script>
          `,
      attributes: {
        title: 'A block'
      },    
  });

The main problem is that the js code is added right after the html rather than at the end of the file

Answers (3)

pouyamiralayiAugust 2, 20192 reactions
Code SnippetTEXT
Hello there! what you are looking for is [here](https://grapesjs.com/docs/modules/Components-js.html)
`
editor.DomComponents.addType('custom-type',{
            model:{
                defaults:{
                    script: function () {
                        console.log('hello world');
                    }
                },
                isComponent(){
                    return true
                }
            },
        })
`
you must **define the custom type** before your **block definition**.
then in your block content modify this line to inject your type:
`
          <div data-gjs-type="custom-type" class="sampleclass">Text<div class="sampleclass2"><div><a>A Link</a></div></div></div>
`
**Notice** that for using custom types, they must be defined in a plugin for the moment. more info [here](https://grapesjs.com/docs/modules/Plugins.html)
cheers.
alikabeer32August 2, 20191 reactions

Thank you.

alikabeer32August 2, 20190 reactions

Thank you.

Related Questions and Answers

Continue research with similar issue discussions.

Paid Plugins That Match This Issue

Curated by issue keywords and label relevance to help you ship faster.

View all plugins

Loading paid plugin recommendations...

Browse Plugin Categories

Jump directly to plugin category pages on the marketplace.