Using jQuery to swap out images and classes

Currently, I am utilizing code to swap out images and toggle classes using jQuery when a specific element is clicked. The issue arises when clicking the element for the second time; it seemingly repeats the same actions as the first click event, despite being triggered based on added or removed classes.

To see this in action, simply locate where the cursor changes into a pointer towards the bottom middle of the screen. Click on that point, and you will notice a button move up to align with the cursor. Upon clicking this button, there will be a fading effect, although the same image appears again, causing confusion.

If you have any insights or solutions, please share!

Check out the DEMO here

//on arrow up click
//fade page out
//replace with open nav

$('.arrow_up').bind('click',function() {
    $('.bg').fadeOut(500);
    setTimeout(function(){
    $('.bg').attr('src', 'other_files/images/bg_open_nav.png');
    }, 500);
    $('.bg').fadeIn(500);
    $('.arrow').removeClass('arrow_up').addClass('arrow_down');
});

//on arrow down click
//fade page out
//replace with closed nav

$('.arrow_down').bind('click',function() {
    $('.bg').fadeOut(500);
    setTimeout(function(){
    $('.bg').attr('src', 'other_files/images/bg.png');
    }, 500);
    $('.bg').fadeIn(500);
    $('.arrow').removeClass('arrow_down').addClass('arrow_up');
});

Answer №1

Once the DOM is loaded, your JS code is already compiled. This means that $('.arrow_up') is defined while $('.arrow_down') is not. The button element assigned to $('.arrow_up') has been initialized and only the events linked to it are being executed.

Consider creating a distinct button for arrow_down and utilize CSS to control its visibility. This approach should help resolve the issue at hand.

Answer №2

Keep it simple. Create a separate div for the arrow pointing down.

Check out this interactive js fiddle for some experimentation. The one you have isn't functioning properly.

https://jsfiddle.net/abc123/

</div>

<div class="navigation">
    <div class="arrow_up arrow">UP</div>
    <div class="arrow_down arrow">DOWN</div>
</div>
<img src="http://vk.com/images/gifts/256/70.jpg" class="background" />
</div>

JS:

//when arrow up is clicked
//fade out background image
//replace with open navigation

$('.arrow_up').click(function() {
    $('.background').fadeOut(500);
    setTimeout(function(){
    $('.background').attr('src', 'http://vk.com/images/gifts/256/78.jpg');
    }, 500);
    $('.background').fadeIn(500);
    //$('.arrow').removeClass('arrow_up').addClass('arrow_down');
});

//when arrow down is clicked
//fade out background image
//replace with closed navigation

$('.arrow_down').click(function() {
    $('.background').fadeOut(500);
    setTimeout(function(){
    $('.background').attr('src', 'http://vk.com/images/gifts/256/70.jpg');
    }, 500);
    $('.background').fadeIn(500);
    //$('.arrow').removeClass('arrow_down').addClass('arrow_up');
});

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

Exploring the utilization of AJAX function within a newly inserted row

On my website, users have the option to click a button labeled "Add Question" in order to insert a new row. Each row will display a CLO value determined by the provided keyword and chapter through the function CLO(). I am attempting to invoke the CLO() f ...

Is there a more efficient or concise way to phrase this?

To simplify my jsfiddle project, I am trying to create a path that loops a certain number of times based on user input. For example, if the user enters a number less than 30, one path (a bottle) will be drawn on the paper. If the number is above 30, two pa ...

Creating 100 unique pages using AngularJS with consistent layout

I'm currently working on an AngularJS application with two templates that are used across 100 different pages. Instead of creating separate static template files for each page, I prefer to use dynamic content within the templates. What would be the b ...

Having Difficulties Initiating Click Actions on Save Buttons Located in Child Components

I'm facing a challenge with triggering click events on save buttons located in child components within my React app. Within my parent component called AddQuestionsPage, I have multiple instances of a child component named Question. Each Question comp ...

Receiving the response from the withTransaction callback in Mongoose

While I appreciate the capabilities of mongoose's withTransaction helper in handling transient transaction errors, it seems that there is a limitation when it comes to returning data. Unfortunately, this poses an issue for my specific needs. The code ...

Selecting elements by class in jQuery tends to be slower compared to selecting by id

My task involves iterating through a group of <ul> elements containing <li>s and filtering them based on a specific word inputted by the user. Initially, I was using IDs for selection which worked well until I encountered duplicate IDs causing ...

Tips for displaying video elements using videojs

Is there a method to echo the data-setup attribute without having to close the php tag and then write html code? I am experiencing a quote mismatch issue. echo '<video-js data-setup='{"controls": true, "autoplay": false,"preload":"auto"}&apos ...

Is there a way for me to verify that the input value matches an email format?

Here is an example that I'm struggling with: link This is the HTML code: <input type="text" name="email" class="email" placeholder="Your email address"> This is the JavaScript code: $(document).ready(function ($) { function validateEm ...

When you use Greasemonkey to click a link embedded within the content

In need of assistance with clicking a dynamic link using Greasemonkey. The only static part of the code is the text 'Attack This Player'. The href attribute of the link changes depending on the page. Here is my current code: function click_elem ...

Retrieve the choices for the second dropdown based on the selection made in the first dropdown

Hello, I need some assistance. I am currently working on implementing 2 dropdown menus. The first one allows me to select the name of a city <select id="select1" class="select" name="city"> <option value="101000000">city1</option> <o ...

Sending a post request from JavaScript to Django Rest Framework

I am working with a DFR api endpoint: url = http://example.com/api/data/ The URL of the page where I am running JavaScript code is: http://example.com/page/1/ I have logged in as User1 in my browser. POST request - from DRF browser API - successful. G ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

How to access the ckeditor function within a dialog HTML element without relying on the "onOk" event

I'm in the process of developing my own plugin and dialog using an html element. I have a requirement where upon clicking the html element, I need to add some text to the editor. However, I'm facing challenges with the onOk function and finding i ...

Having issues with importing images in Next.js using the Next Images package

Having trouble with importing images locally from the images folder. Error message: "Module not found: Can't resolve '../images/banner1.jpg'" https://i.stack.imgur.com/Dv90J.png Attempting to access images in ImagesSlider.js file at compo ...

Silly problem arising from the animate feature in jQuery

Apologies for my poor English. I am facing an issue with the animate function of jQuery in my code snippet. It seems to work fine at line 2, but it doesn't work at line 3. Can someone help me understand why? $('.opac').hover(function(){ ...

What's the deal with using tables or divs in web design? Are they necessary or just a crazy trend?

For my upcoming project, I am eager to take on this task. https://i.sstatic.net/eVSvy.jpg The question remains: which approach should I employ - a Div or table method? ...

What is the proper way to use the setTimeout function in JavaScript?

Given the code snippet below, I am tasked with printing "B" and "C" after "A" in the console after 3 seconds. My attempt was to use: setTimeout(main(),3000); However, I did not receive any output. function sleep(){ } function main(){ console.log(&ap ...

Customizing Cake PHP forms by dynamically displaying or concealing elements depending on the value chosen in

Is there a way to toggle the visibility of form elements in CakePHP based on a dropdown selection? In other frameworks, I would typically use jquery or ajax for this functionality. However, I am struggling to find resources specifically addressing this sc ...

Creating dynamic web content using PHP and JavaScript

I stumbled upon a tutorial on the PHP.net website within the "PHP and HTML" manual which includes an example titled Generating JavaScript with PHP. Currently, I am experimenting with a basic demo of this concept on my own to grasp the process before attem ...

What is the specific event in Angular used to bind the chosen date from a Calendar component?

I'm currently working on an Ionic 4 app using Angular. In the code snippet below, I am trying to figure out how to bind a date after selecting it from the Calendar. Can anyone tell me what event I should use to achieve this? <ion-item> < ...