Anna_B
Anna_B

Reputation: 900

jQuery: If h1 has specific text then link should be added

This is my try so far:

$("h1").each(function() {
  if ($(this).text() == "Google") {
    $(this).click(function() {
      window.open("https://google.com/");
    });
  }
});

$("h1").each(function() {
  if ($(this).text() == "Facebook") {
    $(this).click(function() {
      window.open("https://facebook.com/");
    });
  }
});

$("h1").each(function() {
  if ($(this).text() == "Instagram") {
    $(this).click(function() {
      window.open("https://instagram.com/");
    });
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Google</h1>

If the text of the h1 is for Example Google, then the website link for the Google website should be added. If the text is Facebook, then the website link for the Facebook website should be added. It should update automatically if the h1 changes.

My try does not work unfortunately, and it looks very laborious.

Has someone an idea how to do that in a smart way?

Thanksss <3

Upvotes: 0

Views: 34

Answers (1)

Carsten Massmann
Carsten Massmann

Reputation: 28206

It looks like window.ooen() does not work in the SO snippet. That is why I have added the console.log() here for demo purposes.

$("body").on("click","h1",function() {
  const url=$(this).text().toLowerCase();
  if(["google","facebook","instagram"].indexOf(url)>-1){
   console.log(`opening ${url}`); 
   window.open(`https://${url}.com/`);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Google</h1>
<h2>Google</h2> 
<h1>Instagram</h1>

Upvotes: 1

Related Questions