Issue with toggling classes using a JavaScript button

Learning HTML, CSS, and JavaScript is a new experience for me, and I have been following a project tutorial to grasp the concepts. While troubleshooting a JS button issue for my robot project, I realized that my lack of experience might be hindering my understanding.

The main objective of the project is to create a robot with flashing eyes triggered by a button click. Clicking the button again should stop the flashing effect.

Below is the pertinent code snippet:

<!DOCTYPE html>

<head>
<script src="/assets/jquery.js"></script>
<link href='https://fonts.googleapis.com/css?family=Poller+One' rel='stylesheet' type='text/css'>

<style>
...

/* More sections of robot */

@keyframes blink {
  50% {
    background: radial-gradient(circle, red 15%, transparent 40%), #cc5;
    background-size: 75px 150px;
  }
}
@-webkit-keyframes blink {
  50% {
    background: -webkit-radial-gradient(circle, red 15%, transparent 40%), #cc5;
    background-size: 75px 150px;
  }
}
@-moz-keyframes blink {
  50% {
    background: -moz-radial-gradient(circle, red 15%, transparent 40%), #cc5;
    background-size: 75px 150px;
  }
}

.laser {
  animation: blink 5s infinite;
  -webkit-animation: blink 5s infinite;
  -moz-animation: blink 5s infinite;
}
.brain {

 /* Styles for the robot elements */
  
}
</style>
</head>

<body>

<div class="robot">
  <div class="beep"></div>
  <div class="brain"></div>
  <div class="torso">
    <div class="left">j</div>
    <div class="right">j</div>
  </div>
  <div class="foot"></div>
</div>

<button class="flash">laser eyes on/off</button>
<button class="color">change color!</button>

<script>
// Functionality for the toggle button
$('.flash').click(function() {
  $('.brain').toggleClass('laser');
});

</script>

</body>

I am uncertain if there are any specific issues in my code as I am struggling to identify and rectify them. Despite following the tutorial instructions meticulously, I remain confused about the significance of incorporating more CSS identifiers in HTML elements. Any guidance would be greatly appreciated!

Answer №1

It seems like yet another instance of forgetting to enclose your jQuery code within $(document).ready(function(){})

To resolve this, update your jQuery code to the following:

$(document).ready(function(){
$('.flash').click(function() {
  $('.brain').toggleClass('laser');
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<!DOCTYPE html>

<head>
<link href='https://fonts.googleapis.com/css?family=Poller+One' rel='stylesheet' type='text/css'>

<style>
...

/* Other parts of robot */

@keyframes blink {
  50% {
    background: radial-gradient(circle, red 15%, transparent 40%), #cc5;
    background-size: 75px 150px;
  }
}
@-webkit-keyframes blink {
  50% {
    background: -webkit-radial-gradient(circle, red 15%, transparent 40%), #cc5;
    background-size: 75px 150px;
  }
}
@-moz-keyframes blink {
  50% {
    background: -moz-radial-gradient(circle, red 15%, transparent 40%), #cc5;
    background-size: 75px 150px;
  }
}

.laser {
  animation: blink 5s infinite;
  -webkit-animation: blink 5s infinite;
  -moz-animation: blink 5s infinite;
}
</style>
</head>

<body>

<div class="robot">
  <div class="beep"></div>
  <div class="brain" height="50px">df</div>
  <div class="torso">
    <div class="left">j</div>
    <div class="right">j</div>
  </div>
  <div class="foot"></div>
</div>

<button class="flash">laser eyes on/off</button>
<button class="color">change color!</button>

<script>
// Button to toggle
$(document).ready(function(){
$('.flash').click(function() {
  $('.brain').toggleClass('laser');
});
});

</script>

</body>

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

Jquery alters the border of a textbox with a single modification

I attempted to implement a validation using regular jQuery and managed to accomplish half of it successfully. When I try to submit an empty field, the textbox border turns red, but if I fill in the value and click the button again, the border doesn't ...

C# ASP.NET Dynamic Gridview Expansion

Has anyone found a method to implement a collapsible ASP.NET gridview that can show parent-child relationships when a checkbox is clicked? ...

Organize a collection of objects into a fresh array

I am facing an issue where I have an array and I need to transform it into an array of its children elements. var data = [{ name: 'Cars', content: 'BMW', value: 2000 }, ...

I need assistance in configuring headers for an Ajax request using Oauth 1.0. Can anyone verify if my authorization header setup is correct?

After spending countless hours trying to solve this issue, I am struggling to make it work. I'm unsure if the information I am putting in the authorization header of my Ajax request is correct, especially since there is little informati ...

Using Django templates to include JavaScript files stored in the static directory

I'm facing an issue: within addWorkout.html: {% extends "workout/base.html" %} {% block footer %} <script type="text/javascript" src="{% static js/addWorkout.js %}"></script> {% endblock %} within base.html: {% load static %} <!DOCT ...

Why isn't the npm table populating the command line interface table?

I attempted to create a command line table using npm table, but encountered issues with it. Here is my code and an explanation. const {table} = require('table'); let data; let output; data = [['id','product','name&apos ...

The NextJS App directory consistently stores the retrieved data in the cache, regardless of any no-cache options that may have been configured

Despite trying various online advice, I am still facing the issue of cached fetched data. I am using a mongodb server, and even though I add data to the server, I can only see the new data on the server itself, not on the website (before the NextJS project ...

What is the most efficient method for targeting particular table elements in JavaScript?

In my table, I have both visible and hidden rows like this: -visible- -invisible- -visible- -invisible- My goal is to show the hidden row when a table row is clicked. Currently, I achieved this using the following function: var grid = $('#Billa ...

Enhance the functionality of CKEditor Link feature to emulate the seamless linking experience of Gmail, eliminating

Looking to enhance the CKEditor Link feature to function like Gmail's 'Insert Link' where clicking on it automatically converts text to a link without needing to provide a URL in a popup. Any suggestions? ...

The 3D card flipping animation is dragging on for an eternity

I'm experiencing a delay in triggering my 3D Card Flip animation on click, and I can't figure out why it's happening. If you want to see an example, please scroll down and click on any black and white picture here: Here is the code I' ...

Finding and merging duplicate values within a Javascript array

I am working with a dynamically generated array that looks like this: var myArray = ("0% { left:74px; top:202px; }" , "44% { left:427px; top:122px; }", "0% { font-size:11px; }", "55% { font-size:49px; }" ); Within the array, there are 2 entries that ha ...

Reflections on the Javascript Prototype Design Pattern

After using a Javascript revealing module pattern, I'm now transitioning to a new approach which seems to be working. However, I'm not entirely sure if I'm following the best practices. Specifically, I want to know if my method of preserving ...

Optional URL segment in the middle of AngularJS UI-Router

I am looking to add an optional url segment in the following example: url: "/post/:category/:subcategory/:title/{id:int}", In this scenario, subcategory is not required. It should be able to accept: url: "/post/sports/football/some-title/10", as well a ...

jQuery hotkeys are compatible with all keys, not limited to specific ones

Recently, I implemented the following code on my website: $(document).bind('keydown', 'i', function(){ $("#af").click(); return false;}); After testing the code, I noticed that it responds to all keys pressed, rather than just the let ...

The blending scene in Three.js is flickering with the EffectComposer

I'm a beginner in three.js and I am facing challenges in achieving a specific effect: rendering 2 scenes and blending them with a shader. The first TexturePass is working fine, but the second one is flickering like a strobe light. You can see the resu ...

Eliminate parameter from URL

Here is the URL I am working with: http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860 My goal is to redirect to this URL: http://my.site#/homepage To achieve this, I use the following code snippet: import { push } from 'react-router-redux& ...

Checking for Internet Connectivity in Mobile HTML5

Is it possible to check for internet connectivity on a mobile device? Can websockets be utilized to ping a server and determine if the connection is available? I am feeling frustrated as I believed there was a ping function in websockets for client-side u ...

``req.body is not being properly populated when data is sent using form-data, causing

When I send data in my Node.js application as raw JSON/x-www-form-urlencoded from Postman, it gets passed successfully. However, when sending the data as form-data from either Postman or my Angular frontend, the req.body is coming back as undefined. I have ...

Is there a way to efficiently select and transfer multiple data in the specified format using Vue.js in HTML?

I am struggling with passing the data as per the specified format. rules : [{ name:null, section:null, data : [{head:null,value:null}] }], The challenge I am facing revolves around passing data in this particular format. I h ...

Query inputting time displaying additional numerical values beyond just minutes

I am adding a time field to a table with a length of 6 in the database. Utilizing the Tempos Dominus Bootstrap library for the time within the form HTML Form <div class="form-group"> <label for="time">Hora</label> ...