jQuery: How add JavaScript alerts based on “:contains(…)”, if the text is temporary?

I wanted to change a h1 if a specific div gets clicked. I have already coded this, and it works fine. But: Now, I want to add specific on-click alerts for every headline.

I tried it like this:

// This works:

let myText = "Hello"

$("#one").on("click touchstart", function() {
  myText = "One";
  $("h1").text("One");
  return false;
});

$("#two").on("click touchstart", function() {
  myText = "Two";
  $("h1").text("Two");
  return false;
});

$("body").on("click touchstart", function() {
  myText = "Hello"
  $("h1").text(myText);
});


// This works not:

$("h1:contains('Hello')").click(function() {
  alert("Hello. Some text.");
});

$("h1:contains('One')").click(function() {
  alert("Here is text to One.");
});

$("h1:contains('Two')").click(function() {
  alert("Two is very cool.");
});
* {
  font-family: Arial;
  cursor: default;
}

.active {
  background-color: yellow;
}

div {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  float: left;
}

div:nth-of-type(1) {
  background-color: green;
}

div:nth-of-type(2) {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Hello</h1>

<div id="one">Click me</div>
<div id="two">Click me</div>

For example: If you click the green box, and then the headline that contains a “One”, there should be an alert.

I have tried it with :contains(…), but unfortunately, it does not work.

Would be veeeery thankful for help! <3

And yes, this complexity is necessary, because there will be many other functions integrated in the end.

Answer

Use a switch case to split up your functionality.

// This works:

let myText = "Hello"

$("#one").on("click touchstart", function() {
  myText = "One";
  $("h1").text("One");
  return false;
});

$("#two").on("click touchstart", function() {
  myText = "Two";
  $("h1").text("Two");
  return false;
});

$("body").on("click touchstart", function() {
  myText = "Hello"
  $("h1").text(myText);
});

// If you want to split up functionality
$("h1").click(function() {
  switch($(this).html()) {
  case 'One':
     alert("Here is text to One.");
    break;
  case 'Two':
    alert("Two is very cool.");
    break;
  case 'Hello':
    alert("Hello. Some text.");
    break;
  default:
    // code block
} 
});
* {
  font-family: Arial;
  cursor: default;
}

.active {
  background-color: yellow;
}

div {
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
  float: left;
}

div:nth-of-type(1) {
  background-color: green;
}

div:nth-of-type(2) {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Hello</h1>

<div id="one">Click me</div>
<div id="two">Click me</div>

Leave a Reply

Your email address will not be published. Required fields are marked *