I'm experimenting with jQuery and I made this fiddle.
What it basically does is wherever you click, a div element is appended on the body to that clicked coordinates.
I've managed to do it but I would like to avoid the inline styling, i.e.;
this line : $('body').append('<div style="top:'+y+'px; left:'+x+'px;"></div>');
Is there any way I could do this with any jQuery methods where the CSS can be set for every particular div as soon as it is appended?
If it is to function as your fiddle does, stick with inline styles. To dynamically write CSS into a style tag in the dom for every element, while possible, would be hyper-wonky.
If you like it more jQuery like, you can write it like this:
$('<div/>').css({'top' :y, 'left':x}).appendTo('body');
but that essentially does the same thing you're already doing. See it here
After appending all dynamic elements you can append a style tag directly to the head to avoid any inline style in your code.
E.g.:
$('head').append(
'<style type="text/css">' +
'div{ top: y; left: x}' +
'</style>'
);
You can also use style sheets for performance purposes. See: https://learn.jquery.com/performance/use-stylesheets-for-changing-css/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With