Irene T.
Irene T.

Reputation: 1393

jQuery dynamic div on the fly with a href

I am using the code below to create a dynamic div and inserting it over an image. Everything is working great. I am also get the source from a hidden div, how can I put the source inside the <a href that I am creating with my dynamic div?

My code is:

$(document).ready(function() {

    var tsource = $('#thesource').val();                           
    $(".gdl-blog-full").find("img:first").after("<div style='width:650px; height:30px; float: left; top:0; position: absolute; margin-top:10px;'><div style='height:23px; padding-top:6px; padding-left:4px; padding-right:4px; background-color:#000; opacity:0.7; color:#fff; font-family:Verdana, Geneva, sans-serif; font-size:12px;'>Πηγή: <a href='tsource' style='color:#fff; text-decoration:none; font-family:Verdana, Geneva, sans-serif; font-size:12px;'>MyLink</a></div></div>");

});

And the body:

<div class="gdl-blog-full" style="width:650px; height:390px;">
    <img src="4114feed_L.jpg" alt="4114ed_L" width="650" height="390" class="alignnone size-full wp-image-8519">
    <input type="hidden" id="thesource" name="thesource" value="google.com" />
</div>

Upvotes: 2

Views: 232

Answers (3)

kd12
kd12

Reputation: 1351

yes, using string concatenation you can do this :

$(document).ready(function () {

   var tsource = $('#thesource').val();
   var div_str = "<div style='width:650px; height:30px; float: left; top:0; position:        absolute; margin-top:10px;'><div style='height:23px; padding-top:6px; padding-left:4px; padding-right:4px; background-color:#000; opacity:0.7; color:#fff; font-family:Verdana, Geneva, sans-serif; font-size:12px;'>Πηγή: <a href='" + tsource + "' style='color:#fff; text-decoration:none; font-family:Verdana, Geneva, sans-serif; font-size:12px;'>MyLink</a></div></div>";
   $(".gdl-blog-full").find("img:first").after(div_str );
});

Also if you want to add dynamic html, you can use Underscore js using template you able to insert html by passing parameters to that template.

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

You need to use string concatenation to use the value of variable tsource

$(document).ready(function () {

    var tsource = $('#thesource').val();
    $(".gdl-blog-full").find("img:first").after("<div style='width:650px; height:30px; float: left; top:0; position: absolute; margin-top:10px;'><div style='height:23px; padding-top:6px; padding-left:4px; padding-right:4px; background-color:#000; opacity:0.7; color:#fff; font-family:Verdana, Geneva, sans-serif; font-size:12px;'>Πηγή: <a href='" + tsource + "' style='color:#fff; text-decoration:none; font-family:Verdana, Geneva, sans-serif; font-size:12px;'>MyLink</a></div></div>");

});

visual difference :

enter image description here

Upvotes: 3

tymeJV
tymeJV

Reputation: 104775

String concatenation:

<a href='" + tsource + "'

Upvotes: 3

Related Questions