Jake
Jake

Reputation: 225

Better way to add bootstrap elements to HTML?

Currently I've got some code that populates a warning, which ends up being this:

$('#alertContainer').html('<div class="alert alert-info alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button><strong>Warning!</strong> No valid nodes were found for the path object.</div>');

I can't help but think this is a terrible, ghetto-ized solution, and that I'm simply not utilizing jQuery correctly to create this new element.

So, is there a better, cleaner way to do this?

Upvotes: 1

Views: 222

Answers (1)

Protomancer
Protomancer

Reputation: 139

You might try to put your error code in a function or an object to clean up your script a bit and make it more readable.

Function method:

    function warningCodeCustom(noun) {
  var string = '<div class="alert alert-info alert-dismissible" role="alert">';
  string += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
  string += '<strong>Warning!</strong> No valid ' + noun + ' were found for the path object.';
  string += '</div>';
    return string;
  }

Called by: $('#alertContainer').html(warningCodeCustom('node'));

Object Method: A really simple object breaks apart the code and could enhance readability or debugging later (possibly unnecessarily breaking apart your function for this application but I'm doing it anyway because the objects are pretty neat).

window.MyError = window.MyError || {};

MyError.Toolbox = MyError.Toolbox || {
  self : this,
  init : function() {
    //trigger the warning code bind
    self.warningCodeBind();
  },
  warningCodeBind : function() {
    //if there are no items on the page add content to our alert container
    if(!jQuery('.validNodes, .orOtherNodes').length) {
      jQuery('#alertContainer').html(self.warningCodeCustom());
    }
  },
  warningCodeCustom : function(noun) {
      var string = '<div class="alert alert-info alert-dismissible" role="alert">';
      string += '<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">&times;</span></button>';
      string += '<strong>Warning!</strong> No valid ' + noun + ' were found for the path object.';
      string += '</div>';
        return string;
      }
};

jQuery(window).load( function() {
    MyError.Toolbox.init();
});

I'm unsure what else your code does but the .error() functionality might be useful. Article here

Upvotes: 2

Related Questions