Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a jquery Margin adder class

I am looking for a way to add margin with any number with jquery. It should be something like :

<div class="mr5">Add this text margin-right = 5px</div>
<div class="ml15">Add this text margin-left = 15px</div>
<div class="mt6">Add this text margin-top = 6px</div>
<div class="mb4">Add this text margin-bottom = 4px</div>

and etc ...

<div class="m4">Add this text margin = 4px</div>
<div class="p4">Add this text padding = 4px</div>
...

Is it possible to create jquery code to do this ? Maybe do it for padding to.

Idea : it can used in Bootstrap too , like add automatic padding , margin or even font-size with fs18 to add font-size:18px

Thanks

like image 926
SayJeyHi Avatar asked Feb 15 '16 07:02

SayJeyHi


2 Answers

This is an options. It will work with padding too.

pass in the 'start with' class and the css you want to apply.

it will then use regex to get the value to apply and css to apply it.

function addCss(startClass, css) {
  $('[class^="' + startClass + '"]').each(function() {
    var px, reg = new RegExp(startClass + "(\\d+)", 'g');
    if ((px = reg.exec(this.className)) != null) {
      $(this).css(css, px[1] + 'px');
    }
  });
}

addCss('mr', 'margin-right');
addCss('ml', 'margin-left');
addCss('mt', 'margin-top');
addCss('mb', 'margin-bottom');

//addCss('pl', 'padding-left');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="mr5">Add this text margin-right = 5px</div>
<div class="ml15">Add this text margin-left = 15px</div>
<div class="mt6">Add this text margin-top = 6px</div>
<div class="mb4">Add this text margin-bottom = 4px</div>
<div class="mb40">Add this text margin-bottom = 4px</div>
<div class="mb4">Add this text margin-bottom = 4px</div>
<div class="mb400">Add this text margin-bottom = 4px</div>
<div class="mb4">Add this text margin-bottom = 4px</div>
like image 56
BenG Avatar answered Sep 29 '22 14:09

BenG


Please try this :

$("div").each(function(){
        var _thiss = $(this);
        var div_class = $(this).attr("class");
      var margin = div_class.split("_");

      if(margin[0] == "mr"){
        $(_thiss).css({"margin-right":margin[1]+"px"});
      }
      if(margin[0] == "ml"){
        $(_thiss).css({"margin-left":margin[1]+"px"});
      }
    });
like image 43
JavidRathod Avatar answered Sep 29 '22 15:09

JavidRathod