Reputation: 69
if i have one div box with this css content:
.box
{
border-radius: 18px;
background: blue
width: 260px;
height: 60px;
padding: 10px;
margin: 15px;
border: 2px black solid;
position: absolute;
left: 250px;
top: 5px;
}
is it possible to create a second box with only other width, height, left and top with something like a function call with parameters in JS or something else where I only can change this params and dont need define more css boxes by myself?
Upvotes: 0
Views: 1363
Reputation: 991
Something like this will get you started:
function newBoxElement(cssClass, position, aWidth, aHeight){
var markup = '<div class = "'+cssClass+'"></div>';
$("body").append(markup);
$('.'+cssClass).css({'position': 'absolute', display: 'block', top: position.top, left: position.left, height: aHeight, width: aWidth, border: '1px solid black'});
}
Here's a jsfiddle http://jsfiddle.net/nn3hboon/
Note that the parameter cssClass is a string, position is an object assuming you're using something like $(element).offset(), and width and height are just width and height values you can get from using offsetWidth and offsetHeight on an element.
Upvotes: 1
Reputation: 8858
You can always create css classes by creating a style tag in your header as follows:
$("<style type='text/css'> .newbox{ color:#f00; font-weight:bold;} </style>").appendTo("head");
But in you case since you are already have a css class defined and would like to just change it's attributes, you can simply select that class using class selector in jquery and change its attributes on the fly.
$(document).find(".box").css("width","200px").css("height","300px").css("background-color","green");
Upvotes: 0
Reputation: 2725
this should do it: http://jsfiddle.net/91shfpxm/
$(function(){
var newbox = createBox(200, 300, 100, 50);
$('body').append(newbox);
});
function createBox(w, h, t, l)
{
return $('<div class="box"></div>').css('width', w + 'px').css('height', h + 'px').css('left', l).css('top', t);
}
Upvotes: 2