I am unsure of the process for implementing an OnClick event to modify the colors of a square

Seeking guidance from the more experienced individuals here as I am just starting out. Any help would be greatly appreciated! This might seem simple to many of you, but for me it's quite challenging.

This is how my HTML code looks:

<html>
<head>
    <title> Div, class, id </title>
    <link rel="stylesheet" href="stylesheets/style.css"/>

    <script type="text/javascript" src="javascripts/jquery-2.1.4.min.js"></script>
    <script type="text/javascript" src="javascripts/jFunc.js"></script>

</head>
<body> 

    <div id="Blue" class="yellow"></div>
    <div id="Red" class="Green"></div>
</body>

Here's a snippet from my CSS file:

body {
color: #a280e2;
font: 1.2em/1.4em 'Myriad Pro', Helvetica, Arial, Sans-serif,;
text-align: left;
margin: 0px;
}

.yellow {
background: yellow;
margin: 100 auto;
padding: 20px; 
width: 100px;
height: 100px;
}

.green {
background: green;
margin: 100 auto;
padding: 20px;
width: 100px;
height: 100px;
}

#Blue {
background: #2700ff;
margin: 100 auto;
padding: 20px; 
width: 100px;
height: 100px; 
}

#Red {
background: #ff0000;
margin: 100 auto;
padding: 20px;
width: 100px;
height: 100px;
}

I've also attempted some javascript:

$(".yellow").on("click", function () {
$(this).toggleClass(".yellow");});

Essentially, my goal is to change the blue square to yellow when clicked and the red square to green. Additionally, a popup alert should appear indicating that the colors have changed upon clicking.

Thank you in advance for all your assistance :)

Answer №1

To make your divs interactive, simply attach an EventListener:

JavaScript Method:

const blueDiv = document.querySelector('#Blue'); // Select the Blue div
const redDiv = document.querySelector('#Red'); // Select the Red div

blueDiv.addEventListener('click', function() { // Add click event listener to Blue div
    blueDiv.style.backgroundColor = 'yellow'; // Change background color to yellow
    alert('First Div has been changed!'); // Display alert message
});

redDiv.addEventListener('click', function() {
    redDiv.style.backgroundColor = 'green';
    alert('Second Div has been changed!');
});

Using jQuery:

const blueDiv = $('#Blue');
const redDiv = $('#Red');

blueDiv.on('click', function() { // Add click event listener to Blue div
    $(this).css({backgroundColor: 'yellow'}); // Change background color to yellow
    alert('First Div has been changed!'); // Display alert message
});

redDiv.on('click', function() {
    $(this).css({backgroundColor: 'green'});
    alert('Second Div has been changed!');
});

Answer №2

toggleClass() is the solution you need. Take a look at this live demonstration here

Answer №3

Check out this handy java script snippet to make the magic happen


<script>
$( document ).ready(function() {
console.log( "ready!" );
$( "#Blue" ).click(function() {
$('#Blue').css('background-color', 'yellow');
alert( "Color Changed" );
});
$( "#Red" ).click(function() {
$('#Red').css('background-color', 'green');
alert( "Color Changed" );
});
});

</script>

Enjoy exploring the demo with this complete html file.


    <html>
<head>
    <title> Div, class, id </title>
    <link rel="stylesheet" href="stylesheets/style.css"/>

<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>

<style>
body {
color: #a280e2;
font: 1.2em/1.4em 'Myriad Pro', Helvetica, Arial, Sans-serif,;
text-align: left;
margin: 0px;
}


.yellow {
background: yellow;
margin: 100 auto;
padding: 20px; 
width: 100px;
height: 100px;
}

.green {
background: green;
margin: 100 auto;
padding: 20px;
width: 100px;
height: 100px;
}

#Blue {
background: #2700ff;
margin: 100 auto;
padding: 20px; 
width: 100px;
height: 100px; 
}

#Red {
background: #ff0000;
margin: 100 auto;
padding: 20px;
width: 100px;
height: 100px;
}
</style>

<script>
$( document ).ready(function() {
console.log( "ready!" );
$( "#Blue" ).click(function() {
$('#Blue').css('background-color', 'yellow');
alert( "Color Changed" );
});
$( "#Red" ).click(function() {
$('#Red').css('background-color', 'green');
alert( "Color Changed" );
});
});

</script>


</head>
<body> 

    <div id="Blue" class="yellow"></div>
    <div id="Red" class="Green"></div>
</body>
</html>

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

What is the best way to iterate through a collection of two or more arrays in order to determine the total length of all

https://i.stack.imgur.com/PpFlB.pngI currently have multiple Arrays containing various inputs this.listNumber = [ { "GenericQuestions": [ { "input": "long", }, { "input": & ...

Utilizing a background image in the slick slider

<div id="largeCarousel" style="display:inline-block; float:right;"> <div class="homepage-item" style="padding-bottom:52%; position:relative; box-sizing:border-box;"> <div id="largeCarouselContent" style="position:absolute ...

Discovering when each iteration of a jQuery loop has finished

I am currently working on implementing the open graph API and incorporating a loop through a results callback. Ensuring that I can determine when the loop has finished in order to execute a 'success' function is proving to be challenging. Initi ...

Challenge with loading Ajax pages

I am facing an issue on my page where clicking a button loads a new page using ajax. However, if the button is clicked multiple times (three or more), the jQuery events start repeating. For example, if the new page contains a delete button with a script ...

The rows in the React table are refusing to change color despite the styles being applied; instead, they are coming back

Hey there, Green Dev here! I've been working on a React table where I'm trying to conditionally change the row color. The styles are being passed in, but for some reason they return as undefined. Strangely enough, when I remove my logic and simpl ...

Modify properties with checkbox selection utilizing AJAX and jQuery

I am facing a challenge in my Task resource where I need to change the boolean attribute based on whether a checkbox is checked or not. Despite having everything set up and working smoothly before adding this AJAX checkbox, including CRUD operations tested ...

Tips for managing media queries in HTML emails on Gmail

When sending out my website's responsive HTML emails, I utilize media queries to ensure optimal display. However, I have noticed a discrepancy in how Gmail/Inbox interprets the max-width parameter in the media query. Instead of referencing the HTML em ...

Set a variable to represent a color for the background styling in CSS

My goal is to create an application that allows users to change the background color of a button and then copy the CSS code with the new background color from the <style> tags. To achieve this, I am utilizing a color picker tool from . I believe I ...

What is the best way to create a select box in React that allows for both single and multiple selections?

I recently started utilizing a new package for generating dynamic forms, which can be found at this link. Upon reading through the documentation, I attempted to create a select box as outlined in the instructions provided here. Despite following the step ...

AngularJS unit testing with $httpBackend is impacted by conflicts with UI-Router

Here is a controller that utilizes a submit function: $scope.submit = function(){ $http.post('/api/project', $scope.project) .success(function(data, status){ $modalInstance.dismiss(true); }) .error(function(data){ ...

The font background color appears to be malfunctioning

body { margin: 0; background-color: white; background: linear-gradient(to right, #000000, #ffffff, #ffffff, #000000); line-height:25px; } h2{ color: black; text-align: center; display: block; font-family: 'Montserrat', san ...

How to invoke a function in an isolated scope of AngularJS using JavaScript

We are in the process of gradually switching our application to work with Angular. I have developed an angular module and a directive that aims to connect specific functionality to an HTML element. angular.module('myApp', [ ]) .controller(&ap ...

Adjust the height and eliminate gaps between rotated divisions

I'm currently working on a floating menu that includes several links. I've successfully applied a CSS style to rotate the menu vertically (-90deg), but I'm facing an issue with the height being greater than desired. How can I reduce the heig ...

Aligning columns next to one another using flexbox in a centered manner

I am attempting to create a layout with 3 columns, but I want any extra columns beyond a multiple of 3 to be centered instead of aligned left. While I have made progress, the issue I'm facing is that the additional columns are not centered relative t ...

Having an issue with my Django model not properly saving data when receiving a POST

Just dipping my toes into the world of ajax and Django, so please bear with me for my messy code. I'm facing an issue where my Django model is not saving the response even after receiving a POST request. I'm attempting to create a simple like/di ...

Identify when users reach the end of a webpage through scrolling using mousewheel actions and scroll events

I want to track when a user reaches the end of a page and tries to scroll further, even though there is no more content to see. One of my usability metrics includes identifying dead scrolls, so I need a reliable way to detect when users attempt to scroll ...

I am unable to locate the appropriate TypeScript type for the `displayName` attribute when it is used as a prop for the `type` component

Having trouble finding the correct type as mentioned in the title. After inspecting with DevTools, I have confirmed that every component I am programmatically looking at has Component.type.displayName. For anything that is not an ElementType, the type is a ...

In search of a highly efficient webservices tutorial that provides comprehensive instructions, yielding successful outcomes

I've reached a point of extreme frustration where I just want to break things, metaphorically speaking, of course. For the past week, I've been trying to learn how to create a web service using C# (whether it's WCF or ASMX, I don't rea ...

Is there a way to achieve a full-page inset shadow using absolute positioned elements?

Currently, I am facing a challenge with a page that has an inset box shadow on the body element. When there are absolute and relative positioned divs on the page that expand enough to generate a scrollbar, the box shadow is cut off even when the height is ...

Tips for accessing the value stored within the parent element

As someone who is new to the world of javascript and typescript, I am currently working on an ionic application that involves fetching a list of values from a database. These values are then stored in an array, which is used to dynamically create ion-items ...