The function addClass() seems to be malfunctioning

I'm currently experimenting with creating a scrolling cursor effect on a string of text. The goal is to make it look like the text has been highlighted with a blinking cursor, similar to what you see in your browser's search bar.

window.setInterval(function(){
if($('.cursorBlink').hasClass('blink')){
    $('.cursorBlink').addClass('blinkOff');
}


if($('.cursorBlink').hasClass('blinkOff')){
    $('.cursorBlink').removeClass('blinkOff').addClass('blink');
}
}, 1000);

The code snippet above sets up an interval to add and remove CSS classes every second, but for some reason, it doesn't work as intended. Interestingly, if I include an alert() function within the intervals, it somehow corrects the issue, which is quite puzzling.

You can view the interactive example on my jsfiddle page. I've added the alert() function there to demonstrate how it affects the outcome (set to run every 3 seconds to avoid annoyance).

Check out the Example on JSFiddle

Answer №1

It seems that the coding logic you have used is a bit convoluted. To simplify, consider using toggleClass() for a single call:

window.setInterval(function () {
    $('.cursorBlink').toggleClass('blinkOff');
}, 3000);

View updated fiddle here.

Additionally, to prevent a slight jump that occurs when removing the class, set the border color to transparent instead of completely removing it:

.blinkOff {
    border-left-color: transparent;
}

Furthermore, this effect can be achieved using only CSS without any JavaScript at all:

.blink {
    border-left: 1px solid white;
    animation: blinker 6s step-start infinite;
}
@keyframes blinker {  
  50% { border-left-color: transparent; }
}

Check out an example fiddle for reference.

Answer №2

First, you apply the class blinkOff, and then you immediately check if it includes the blinkOff class. Since you just added it, it will always be there, so you then remove it.

Your code should be adjusted as follows:

if () { }
if () { }

to:

if () { }
else { }

or at least:

if () { }
else if () { }

Answer №3

Take a moment to enhance your reasoning skills. Consider the following:

window.setInterval(function(){
    if($('.cursorBlink').hasClass('blink')){
        $('.cursorBlink').addClass('blinkOff');
        $('.cursorBlink').removeClass('blink');

    }else{
        $('.cursorBlink').addClass('blink');
        $('.cursorBlink').removeClass('blinkOff');
    }
}, 3000);

https://jsfiddle.net/abc123de/

Answer №4

It seems that by replacing the second 'if' statement with an 'else', the code should work properly. Otherwise, both 'if' conditions will always be executed.

window.setInterval(function(){
    if($('.cursorBlink').hasClass('blink')){
        $('.cursorBlink').removeClass('blink').addClass('blinkOff');
    }
    else{
        $('.cursorBlink').removeClass('blinkOff').addClass('blink');
    }
}, 500);

Answer №5

In this particular scenario, the second condition within the if statement is executed immediately after the first condition, causing the removal of the class that was just added in the first condition. To achieve the desired outcome, consider the following revised code:

window.setInterval(function(){
    if($('.cursorBlink').hasClass('blink')){
       $('.cursorBlink').removeClass('blink').addClass('blinkOff');
    }        
    else {
        $('.cursorBlink').removeClass('blinkOff').addClass('blink');
    }
  }, 1000);

Answer №6

Rory's suggestion is spot on. All you need to do is make slight adjustments to your current code in order to achieve the desired result.

window.setInterval(function(){
    if($('.cursorBlink').hasClass('blinkOff')){
        $('.cursorBlink').removeClass('blinkOff').addClass('blink');
    }
    else {
        $('.cursorBlink').removeClass('blink').addClass('blinkOff');
    }
}, 3000);

Check out the updated Fiddle here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a CSV file using an AJAX request in PHP

In my current project involving PHP AJAX DATATABLE within the Drupal framework, I have successfully developed a function to create a CSV file from table records. This function is triggered by clicking a button in HTML or accessing a specific URL. The PHP ...

Display a container using Fancybox

With just a click of a button, I want to reveal a hidden div in an elegant box. Here's the code snippet that actually works: $("#btnForm").fancybox({ content: $("#divForm").html() }); However, after doing some research, it appears that this may not ...

Navigating Angular: Discovering Route Challenges in Less Than an Hour

Can someone take a look at my code and help me out? I'm trying to learn Angular.js by following the popular Angular.js in 60 minutes video tutorial, but it seems like things have been updated since then. I'm having trouble getting my routes to wo ...

The function client.guilds.find cannot be located

Hey there! I've been tasked with working on a Discord bot that requires several dependencies to function properly. I've installed the necessary dependencies and attempted to run the bot using 'forever -o out.log bot.js'. However, I enc ...

Can you explain the distinction between App: React.FunctionComponent and App = (): React.FunctionComponent()?

Currently exploring the depths of typescript. Can someone clarify the distinction between these two code snippets: const App: React.FunctionComponent<CustomProps> = (props: CustomProps) => { return <div>Hello World!</div>; }; and: ...

Convert object to JSON format using AJAX request to a PHP file

Despite receiving a 200 green response, my data is still not getting written to the json file and it remains blank. The JavaScript: $(function() { $('form#saveTemp').submit(function() { let savdAta = JSON.stringify($('form#save ...

Simple methods for ensuring a minimum time interval between observable emittance

My RxJS observable is set to emit values at random intervals ranging from 0 to 1000ms. Is there a way to confirm that there is always a minimum gap of 200ms between each emission without skipping or dropping any values, while ensuring they are emitted in ...

Steps to insert an HTML tag with jQuery

Below is a function I have written to display AJAX response in HTML: function loadData() { $.ajax({ type: "post", url: "http://127.0.0.1/get_scroll_rec/", cache: false, data:'&apo ...

How to use JavaScript regular expressions to extract the content following the second-to-last occurrence of a back

I currently have a regular expression that looks like this: /^.*[\\\/]/ At the moment, it removes every single backslash from a string. However, now I need to modify it in order to capture everything after the second to last backslash. Fo ...

Intersection of content in panel-body using bootstrap tab pills

Can someone help me solve a major issue? I need the content of each tab to overlap as if they are unaware of each other. Currently, my code is saved in this fiddle: https://jsfiddle.net/axq882de/1/. When I click on different tabs, the contents should remai ...

The React app hosted on Firebase displays a message saying "please activate JavaScript to run this application"

I created a web app using React that is hosted on Firebase Hosting, with a backend server utilizing Express and Cloud Functions. You can access the website here: The landing, login, and signup pages are functioning properly. However, when trying to acces ...

Using a wildcard (*) to select elements with JQuery

I'm just starting to learn about JQuery and could use some help. I want to select multiple elements but I only know part of their Ids: for example: <div id="element32422455">Some content</div> <div id="element68475124">Some content& ...

Unable to select the option in select2

While attempting to implement select2 jQuery, I encountered an issue where the data retrieved from the database was displayed properly as I typed in the input field and scrolled through the options, but I was unable to click on any of the displayed data. I ...

Looking to enhance code by using jQuery to substitute numerous href elements. Only seeking enhancements in code quality

I am currently using regular JavaScript to change the href of 3 a-tags, but I want to switch to jQuery for this task. var catNav = $('ul.nav'), newLink = ['new1/','new2','nwe3/']; catNav.attr('id','n ...

The Reliability of Using CSS Pixel Font Sizes

Imagine I need to display two capital 'T's, each exactly one inch tall. One 'T' appears on a Macbook Pro with Retina Display (220 DPI, CSS pixel ratio 2), and the other on an iPhone 4S (326 DPI, CSS pixel ratio 2). To achieve this, I se ...

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

The upper border is missing from the middle div in the presence of three divs

I am currently working on a new project using HTML, CSS, and Bootstrap. However, I have encountered a problem. I have created a box with a border all around it, and when I hover over this box, an image appears inside of it. By default, the inside of the bo ...

What is preventing me from accessing arguments.callee within this function in sloppy mode?

In attempting to retrieve the arguments.callee property in the following basic function, I encountered an error preventing me from doing so. function foo(a = 50, b) { console.log(arguments.callee); } foo(10, 50); Why is this issue occurring? It appe ...

Encountering a HttpMediaTypeNotAcceptableException while making a jQuery ajax request after upgrading to Spring 3.2.4版本

Whenever I attempt to execute a jQuery ajax call, I am facing the HttpMediaTypeNotAcceptableException. The current configuration that I have includes: Within the context (which is in the classpath), I have the following: <context:component-scan base- ...

Enhance your slideshow with a stylish fade effect

I found this slideshow on codepen and decided to customize it to make it my own. While everything is working well, I wanted to incorporate a fade effect into the transition between slides. I'm unsure whether I should add something to the CSS file or m ...