diamond421
diamond421

Reputation: 145

How do I pass an Event as a function parameter in HTML written inside JavaScript variable?

I am storing some html in variable after successful ajax call and appending that html to a div. Everything is fine except the event parameter. When I am passing event as a parameter of a java script function,it's appending the img html to the div but on clicking the image I am getting 'Unexpected identifier' error. Here is the code:

 var dataToAppend = "<img onclick='getImgSrc("+event+")' data-toggle='modal' data-target='#msgPhotoModal' class='modal-message-img getSrc' src='" + data[i].ImgUrl + "' />" +

When I am debugging dataToAppend variable I am getting:

<img onclick='getImgSrc([object Event])........'

and the function is:

   function getImgSrc(e) {
        debugger;
        var src = $(this).attr('src');
        $('.msgImg').attr('src', src);
    }

Also var src = $(this).attr('src'); is giving me 'undefined'. What am I doing wrong?

Upvotes: 0

Views: 70

Answers (2)

Tyler Roper
Tyler Roper

Reputation: 21672

You're passing the event. An event is not the same as the element - therefore it doesn't have attributes like src.

First off, let's consider what the HTML needs to look like:

<img src="/images/MyImage.jpg" onClick="getImgSrc(this);" />

As you can see, the parameter is simply the word "this" - it won't require concatenation. Creating this HTML in JavaScript would be done like so:

var dataToAppend = "<img onclick='getImgSrc(this)' ... ";

Also, consider renaming your e parameter to something a bit more descriptive. e often refers to the event, but since we're no longer using that, it's a bit of a misnomer.

Upvotes: 0

palaѕн
palaѕн

Reputation: 73936

Try to change the dataToAppend variable by passing this directly like:

var dataToAppend = "<img onclick='getImgSrc(this)' data-toggle='modal'..."

and modify the function like:

function getImgSrc(obj) {
    debugger;
    var src = $(obj).attr('src');
    $('.msgImg').attr('src', src);
}

Upvotes: 1

Related Questions