Troubleshoot: Unable to Change CSS on Click Using Javascript/jQuery

Having trouble creating three different buttons that toggle between various images using the CSS display property? Check out my code on https://jsfiddle.net/agt559e8/.

function USradarChange1() {
    //document.getElementById("usradar1").src="weather/current-usradar.gif";
    $('#USradarChangeButton1').click(function() {
        $('#usradar1').css({ 'display': 'inline' });
        $('#usradar2').css({ 'display': 'none' });
        $('#usradar3').css({ 'display': 'none' });
    });
}

function USradarChange2() {
    //document.getElementById("usradar2").src="weather/usradar-an12hour.gif";
    $('#USradarChangeButton2').click(function() {
        $('#usradar1').css({ 'display': 'none' });
        $('#usradar2').css({ 'display': 'inline' });
        $('#usradar3').css({ 'display': 'none' });
    });
}

function USradarChange3() {
    //document.getElementById("usradar3").src="weather/usradar-an7day.gif";
    $('#USradarChangeButton3').click(function() {
        $('#usradar1').css({ 'display': 'none' });
        $('#usradar2').css({ 'display': 'none' });
        $('#usradar3').css({ 'display': 'inline' });
    });
}
<div class="button-container">
    <a class="button" id="USradarChangeButton1">Current US Radar</a>
    <a class="button" id="USradarChangeButton2">US Radar 12 Hours</a>
    <a class="button" id="USradarChangeButton3">US Radar 7 Days</a>
</div>

<div id="imgcontainer">
    <img class="radar-img" id="usradar1" src="weather/current-usradar.gif" alt="Current US Radar">
    <img class="radar-img" id="usradar2" src="weather/usradar-an7day.gif" alt="Current US Radar">
    <img class="radar-img" id="usradar3" src="weather/usradar-an12hour.gif" alt="Current US Radar">
</div>

Need help figuring it out? Let me know your thoughts!

Answer №1

Your code has a few issues that need to be addressed. Firstly, there are some functions defined in the code that are never actually called, which means that the event hooks within them are never bound. Additionally, there are mis-matched braces and the fiddle provided does not include jQuery itself.

Aside from these issues, your code can benefit from implementing DRY principles. Here's a revised version:

<div class="button-container"> 
    <a class="button" id="USradarChangeButton1" href="#usradar1">Current US Radar</a>
    <a class="button" id="USradarChangeButton2" href="#usradar2">US Radar 12 Hours</a>
    <a class="button" id="USradarChangeButton3" href="#usradar3">US Radar 7 Days</a>
</div>

<div id="img-container">
    <img class="radar-img" id="usradar1" src="http://trendting.com/wp-content/uploads/2014/05/giphy-225.gif" alt="Current US Radar" />
    <img class="radar-img" id="usradar2" src="https://media3.giphy.com/media/H3MXq3XT4z2ec/200_s.gif" alt="US Radar 12 Hours" />
    <img class="radar-img" id="usradar3" src="http://media.giphy.com/media/10Ocy3t9qoSOwE/giphy.gif" alt="US Radar 7 Days" />
</div>
$(function() {
    $('.button').click(function(e) {
        e.preventDefault();
        $('#img-container img').hide();
        $($(this).attr('href')).show();
    });
});

Take a look at this example fiddle for reference.

Keep in mind that with this updated code snippet, a single click handler will now work for all elements with the class "button", as they are now associated with the relevant div using the href attribute.

Answer №2

If you're not utilizing the 3 functions that have been defined, your code won't work properly.

Make sure to place your jQuery code within the $(document).ready() function.

$(document).ready(function(){
$('#USradarChangeButton1').click(function() {
            $('#usradar1').css({
                'display': 'inline'
            });

            $('#usradar2').css({
                'display': 'none'
            });

            $('#usradar3').css({
                'display': 'none'
            });
        });

//BUTTON 2 CODE
//BUTTON 3 CODE

});

Answer №3

The issue lies in the fact that your handling code is not being executed as it resides within functions that are never called (such as USradarChange3). You have a couple of options to address this problem:

  • Trigger the functions so that the binding code inside them runs.
  • Alternatively, you can eliminate the functions altogether, removing the need to call them for the binding to occur.

In addition, it appears that jQuery is missing from the jsFiddle which could be causing complications. If jQuery is indeed present, ensure that everything is enclosed within a ready handler to guarantee that all elements are loaded before binding takes place.

Answer №4

It seems like your approach is incorrect; the current binding of the function to the click event only occurs after the user clicks on the button.

To resolve this issue, it is recommended to bind these three functions when the DOM has finished loading.

$(function(){
    $('#USradarChangeButton1').click(function() {
        $('#usradar1').css({'display': 'inline'});
        $('#usradar2').css({'display': 'none'});
        $('#usradar3').css({'display': 'none'});
    });

    $('#USradarChangeButton2').click(function() {
        $('#usradar1').css({'display': 'none'});
        $('#usradar2').css({'display': 'inline'});
        $('#usradar3').css({'display': 'none'});
    });

    $('#USradarChangeButton3').click(function() {
        $('#usradar1').css({'display': 'none'});
        $('#usradar2').css({'display': 'none'});
        $('#usradar3').css({'display': 'inline'});
    });
});

Answer №5

Initially, I noticed that the jQuery library was missing from the fiddle, and upon further inspection, syntax errors were discovered.

A function was declared where a 'click' event was registered, but this approach will not work as intended.

Below are two methods to help you achieve your desired outcome:

$('#USradarChangeButton1').click(USradarChange1);
$('#USradarChangeButton2').click(USradarChange2);
$('#USradarChangeButton3').click(USradarChange3);

function USradarChange1() {
    $('#usradar1').css({ 'display': 'inline' });
    $('#usradar2').css({ 'display': 'none'});
    $('#usradar3').css({ 'display': 'none'});
}

// Repeat similar functions for USradarChange2 and USradarChange3

Alternatively, you can directly apply the changes without declaring separate functions like this:

$('#USradarChangeButton1').click(function(){
    $('#usradar1').css({ 'display': 'inline' });
    $('#usradar2').css({ 'display': 'none'});
    $('#usradar3').css({ 'display': 'none'});
});

// Repeat similar click events for Button2 and Button3 with corresponding display configurations

I hope this explanation proves helpful to you in resolving the issues. Thank you.

Answer №6

Several corrections need to be made here. First, include the jQuery library in jsFiddle by following this link.

Secondly, the functions provided are not being called, which means the click handlers are not binding to the buttons.

Thirdly, ensure that all actions are performed after the content is fully loaded. The corrected code should resemble the following:

$(document).ready(function () {
    $('#USradarChangeButton1').click(function (event) {
        event.preventDefault();
        $('#usradar1').css({
            'display': 'inline'
        });
        $('#usradar2').css({
            'display': 'none'
        });
        $('#usradar3').css({
            'display': 'none'
        });

    });


    $('#USradarChangeButton2').click(function (event) {
        event.preventDefault();
        $('#usradar1').css({
            'display': 'none'
        });
        $('#usradar2').css({
            'display': 'inline'
        });
        $('#usradar3').css({
            'display': 'none'
        });
    });


    $('#USradarChangeButton3').click(function () {
        event.preventDefault();
        $('#usradar1').css({
            'display': 'none'
        });
        $('#usradar2').css({
            'display': 'none'
        });
        $('#usradar3').css({
           'display': 'inline'
        });
    });

})

Make sure to include event.preventDefault() to prevent the default behavior of links.

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

Executing a CRM javascript button triggers a request to a JSON URL and extracts a specific value

My current task involves creating a button in JavaScript due to system limitations preventing the use of HTML. This button should navigate to a specific URL (REST API to retrieve a JSON file). Furthermore, upon clicking the button, I aim to display an aler ...

Obtain precise JSON information using Node.js

Having limited experience with Angular JS and Node JS, I find myself in need of assistance. On the server side, I have multiple JSON files containing language translations. Based on a client's request for a specific language, such as French, I must re ...

Issue with EaselJS: mouse events are no longer functional

I'm currently working on adding a touch animation using the EaselJs library. Interestingly, when I load an image from a local folder, all mouse events work as expected, such as onPress. However, things take a different turn when I opt to use an imag ...

Retrieving information from a dynamically generated HTML table using PHP

I have successfully implemented functionality using JavaScript to dynamically add new rows to a table. However, I am facing a challenge in accessing the data from these dynamically created rows in PHP for database insertion. Below, you will find the HTML ...

Determining the distance between two points in miles using Next.js

Are you familiar with the concept of geographical coordinates? Take for example these two points: point1 = {lat: 40.6974034, lng: -74.1197636} point2 = {lat: 42.694034, lng: -75.117636} My goal is to find the distance between these two poi ...

Updating radio button based on selection change in jQuery

I'm struggling with jQuery and can't seem to figure out how to change the selected radio button based on a value in another select box. <div class="radio-inline" id="sourceDiv" role="group"> <input type="radio" id="sourceBtns1" na ...

State is not currently utilizing the variable

const DonorsTables = () =>{ const [search, setSearch] = useState(""); const [countries, setCountries] = useState([]); const [filteredcountries, setFilteredCountries] = useState([]); const getCountries = async () => { try { ...

Why is the validate function not being executed in the Backbone Model?

I am a beginner in learning Backbone and I am attempting to implement simple validation in my Person Model. However, I am facing an issue where the validate method does not run when I set a new age. Can someone guide me on where I might be making a mistake ...

Intermittent issues with requesting JSON data

My current project involves building a script that iterates through a list, retrieves product SKUs, and includes them in a JSONP request to retrieve an object. The script seems to be functioning as intended, but there are occasional failures. Here is an e ...

What is the method for determining the height of a div element when it is set to 'height=auto'?

I am trying to determine the height of a specific div using Javascript. Here is the script I have written: function getMainDivHeight() { var num = document.getElementById('up_container').style.height; return num; } However, this script ...

Animating a div's width with CSS from left to right

My goal is to create an animation effect for two overlapping divs that will reveal or hide the text inside them. I want one div to animate from left to right while the other animates from right to left, creating a wiping effect where as one piece of text d ...

Enable search functionality for jQuery Select2 values that have been formatted by a formatter function

Trying to use a formatter with select2 for better alignment of code and description elements, but the plugin seems to be searching based only on the description rather than the entire text. This may be because it's only looking at the original <opt ...

Customized figcaption formatting separate from the surrounding text

Is there a way to add a "figcaption" with independent settings to images placed alongside paragraphs in HTML? I have the following code snippet, but I'm unsure if I am using the figcaption tag correctly: <p><figure><span class="image ...

Issue encountered while trying to define a global variable within a JavaScript Class

I'm currently working on setting up a page variable that can be utilized by my Scroller class for implementing infinite scrolling. It's crucial for this variable to have global scope, as it needs to retain its value outside of the ajax function. ...

Struggling to resolve a common issue in Migration? It seems that a raw query in Sequelize is adding backslashes that are causing errors when inserting values into the database

During migration, data is taken from one table and inserted into another. However, an issue arises when Sequelize adds backslash escape characters to the 'v_occupation' value, causing insertion errors. I have attempted various replacements and m ...

Encountering a "focus" error with React-Native-Phone-Input library, where the property is null

For my project, I decided to incorporate the react-native-phone-input library. Everything was going smoothly until I encountered an issue with their focus function. Initially, it worked perfectly fine, but subsequently, when I attempted to input a phone nu ...

alert the Q Promise progress within a Node.js environment

When attempting to utilize the Q Promise Progress feature, my code is designed to catch progress and resolve the Promise once progress reaches 100. Here is the specific code snippet: var q = require("q"); var a = function(){ return q.Promise(functio ...

Changing the color of text in an HTML input field using CSS and JavaScript depending on the input value

Looking for a solution! // Getting user input values var input1 = parseInt(document.getElementById("input1").value); var input2 = parseInt(document.getElementById("input2").value); var input3 = parseFloat(document.getElementById(" ...

Form Input Field with Real-Time JavaScript Validation

Is there a way to validate the content of a textarea using pure JavaScript, without using jQuery? I need assistance with this issue. <script> function validate() { // 1. Only allow alphanumeric characters, dash(-), comma(,) and no spaces ...

Is it possible to have the background blurred, but only specifically behind the overlay?

How can I make the div appear as if it is blurring the background image of the page, even when the position of the div is changed? Also need to ensure it works seamlessly during window resizing. ...