Add onclick event to created element with createelement

Asked

Viewed 7,871 times

3

I have the following code:

FForm.prototype._addControls = function() {

    // main controls wrapper
    this.ctrls = createElement( 'div', { cName : 'fs-controls', appendTo : this.el } );

    // continue button (jump to next field)
    **this.ctrlContinue = createElement( 'button', { cName : 'fs-continue', inner : 'Proxima', appendTo : this.ctrls } );**

    this._showCtrl( this.ctrlContinue );

    // navigation dots
    if( this.options.ctrlNavDots ) {
        this.ctrlNav = createElement( 'nav', { cName : 'fs-nav-dots', appendTo : this.ctrls } );
        var dots = '';
        for( var i = 0; i < this.fieldsCount; ++i ) {
            dots += i === this.current ? '<button class="fs-dot-current" ></button>' : '<button disabled></button>';
        }
        this.ctrlNav.innerHTML = dots;
        this._showCtrl( this.ctrlNav );
        this.ctrlNavDots = [].slice.call( this.ctrlNav.children );
    }

    // field number status
    if( this.options.ctrlNavPosition ) {
        this.ctrlFldStatus = createElement( 'span', { cName : 'fs-numbers', appendTo : this.ctrls } );

        // current field placeholder
        this.ctrlFldStatusCurr = createElement( 'span', { cName : 'fs-number-current', inner : Number( this.current + 1 ) } );
        this.ctrlFldStatus.appendChild( this.ctrlFldStatusCurr );

        // total fields placeholder
        this.ctrlFldStatusTotal = createElement( 'span', { cName : 'fs-number-total', inner : this.fieldsCount } );
        this.ctrlFldStatus.appendChild( this.ctrlFldStatusTotal );
        this._showCtrl( this.ctrlFldStatus );
    }

    // progress bar
    if( this.options.ctrlProgress ) {
        this.ctrlProgress = createElement( 'div', { cName : 'fs-progress', appendTo : this.ctrls } );
        this._showCtrl( this.ctrlProgress );
    }
}

Notice there’s a createElement creating a button. I need some code to be executed in the event when I click on that element that was created, what should I do ?

Here has a demo of the example I’m using.

5 answers

6

The method createElement (Documentation of the MDN) returns an object, which you are already storing in ctrlContinue. To add an event to this object, just do the following:

ctrlContinue.addEventListener('click', function() { ... })

And trade function() { ... } by the function that contains the code you want to execute. I also recommend looking at the documentation of the method addeventlistener

4

You must use the following code;

//CRIA O ELEMENTO
var botao = document.createElement('button');

//ADICIONA O ONCLICK
botao.onclick = function () {
    alert('HUE BR');
};
  • Simple and good solution, thanks!

3

You could do it like this:

   for( var i = 0; i < this.fieldsCount; ++i ) {
      var button = document.createElement('button');
      i === this.current ? button.addClass('fs-dot-current') : button.setAttr('disabled');
      //AddEventListener só funciona IE9+
      button.onclick = function (e) {}   
      this.ctrlNav.appendChild(button);
   }
  • 1

    Just be careful not to use i within this onclick function, as it will go wrong.

2


What javascript framework are you using? The correct syntax is

document.createElement(tagName)

and its syntax is :

createElement( 'button', { cName : 'fs-continue', inner : 'Proxima', appendTo : this.ctrls } ); 

i.e., it is a function call and not a method of an object.

To give a correct answer you need to know how this function works, but starting from the principle that returns a button object then you can add an event as follows:

That is the function

/**
     * createElement function
     * creates an element with tag = tag, className = opt.cName, innerHTML = opt.inner and appends it to opt.appendTo
     */
    function createElement( tag, opt ) {
        var el = document.createElement( tag )
        if( opt ) {
            if( opt.cName ) {
                el.className = opt.cName;
            }
            if( opt.inner ) {
                el.innerHTML = opt.inner;
            }
            if( opt.appendTo ) {
                opt.appendTo.appendChild( el );
            }
        }   
        return el;
    }

and as I predicted, this function returns the element.

You can, in principle, use the code below to connect a "click event"

try{

this.ctrlContinue.addEventListener('click', function() { alert("ok) });

} cath(e){

//compatibilidade com IE
this.ctrlContinue..attachEvent("onclick", function() { alert("ok) })
}
  • Manuel, I am using this framework http://tympanus.net/codrops/2014/07/30/fullscreen-form-interface/ thank you

  • @hulck see the edition I made. If you need anything else, have

  • 1

    Thank you very much Manuel, it worked. Hugs

0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.