Steve Gates
Steve Gates

Reputation: 195

Changing meta-tags dynamically with jQuery

I have a page with several paragraphs, when a user clicks on the 'snapshot' button beside a paragraph, the paragraph is reproduced on a canvas as an image and displayed above the original paragraph.

Beside the snapshot paragaph is a 'share' button, how do I change the url of the following meta-tag content to the url of the snapshot paragraph on the click of the 'share' button.

share button

<a href="#" id="share">Share?</a>

BEFORE SHARE BUTTON CLICK

<meta name="twitter:image" content="p.jpg">

AFTER SHARE BUTTON CLICK

<meta name="twitter:image" content="image/paragraphxi34343.jpg">

Any solutions?

Upvotes: 3

Views: 3621

Answers (2)

Aurelio Tontini
Aurelio Tontini

Reputation: 1

$('head meta[name=twitter:image]').attr('content', 'image/paragraphxi34343.jpg');

Take a look at : https://api.jquery.com/attr/

Upvotes: 0

kiranvj
kiranvj

Reputation: 34117

Not sure if this is optimized way to do it, but this should work.

$("meta").each(function() {

  if($(this).attr("name") == "twitter:image") {
    $(this).attr("content" , "image/paragraphxi34343.jpg");
  };
});

A more generic way would be

function changeMetaContent(metaName, newMetaContent) {
    $("meta").each(function() {

      if($(this).attr("name") == metaName) {
        $(this).attr("content" , newMetaContent);
      };
    });
}

Call like

changeMetaContent("twitter:image", "image/paragraphxi34343.jpg");

Updated after discussion in comments

If you have the url in an input field do this.

<input value="http://some-image-url.png" type="hidden" id="image-url-input" />

Call the function like this;

var imageURL = $("image-url-input").val();
changeMetaContent( "twitter:image", imageURL );

Upvotes: 1

Related Questions