Tiny Tiny - 6 months ago 25
Javascript Question

Text colour highlighting using JavaScript



//<![CDATA[
var blinkText = $(".highlight");

var interval = setInterval(function() {
blinkText.toggleClass("highlightRed");
}, 500);
//]]>

.highlight {
-webkit-transition: background 1.0s ease-in-out;
-ms-transition: background 1.0s ease-in-out;
transition: background 1.0s ease-in-out;
}
.highlightRed {
color: red !important;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="highlight" style="font-weight: bolder; font-size: 33px; color: #00F">&rarr;</span>





JSFiddle:

The above code is expected to make the given arrow blink according to the interval given but it does not. How to make the arrow change colour with respect to the interval given?

Answer

You need to change following things to make your code work.

  1. Attach jQuery to your web page.
  2. Use your JavaScript code in inside $(function() { ... }); code so that it founds elements in DOM
  3. Move your inline styles to the stylesheet attached.
  4. Styles of highlightRed class should come after styles of .highlight in stylesheet.

Note: no need to use !important in your styles. It should be avoided as much as possible.

$(function() {
  var blinkText = $(".highlight");

  var interval = setInterval(function () {
      blinkText.toggleClass("highlightRed");
  }, 500);
});
.highlight {
    -webkit-transition: background 1.0s ease-in-out;
    -ms-transition: background 1.0s ease-in-out;
    transition: background 1.0s ease-in-out;
    font-weight: bolder;
    font-size: 33px;
    color: #00F;
}

.highlightRed {
    color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<span class="highlight">&rarr;</span>