2

i have an script that i want to generate i div where ever user clicks and that div stays there so now i have this jquery script

$(document).ready(function() {
    $('body').click(function(e) {
        var offset = $(this).offset();
        $('#x_axis').html(e.clientX - offset.left);
        var x = (e.clientX - offset.left);
        $('#y_axis').html(e.clientY - offset.top);
        var y = (e.clientY - offset.top);
        $('body').append('<div id="bloom" style="position: relative; left: HERE I WANT TO PLACE X;">asd</div>');
        $('#bloom').css('left', x);
        $('#bloom').css('top', y);
    });
});

now on this line i want to add my X and Y variables to left and top attribute :

            $('body').append('<div id="bloom" style="position: relative; left: HERE I WANT TO PLACE X;">asd</div>');

any idea how this can be done ?? or any better way to make this thing that when user click on each part of page a div generates there

2
  • Three (edit: four) answers, and none of them do it properly. $('body').append($('<div>').attr('id', "bloom").css({ position: "relative", left: x }).text("asd")); Commented Jan 26, 2019 at 7:38
  • Also note that you don't want to "use jquery variable in inline css", what you want to do is "insert a variable into a string", a problem which is much easier to solve via Google. You need to cut irrelevant stuff from your problem before plugging it into a search engine. Commented Jan 26, 2019 at 7:41

4 Answers 4

3

You can use template literals for that

Solution

  $('body').append(`<div id="bloom" style="position: relative; left: ${x};">asd</div>`);

More about template literals

Sign up to request clarification or add additional context in comments.

2 Comments

should i add any thing to my project because thats not working it just out puts ${x} in html
use `` instead of '' for the enclosure,
2

You can directly place by adjusting the ''

$('body').append('<div id="bloom" style="position: relative; left:'+x+';">asd</div>');

Comments

1

you can concatenate the variable

eg:

 $('body').append('<div id="bloom" style="position: relative; left:' + x + ';">asd</div>');

or

use template literals

$('body').append(`<div id="bloom" style="position: relative; left:${x};">asd</div>`);

1 Comment

should i add any thing to my project because thats not working it just out puts ${x} in html
1

You can concat the javascript variable in this format:

 $('body').append('<div id="bloom" style="position: relative; left:' + x + ';">asd</div>');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.