Creating a fading effect on an image in relation to another dynamic image

I am currently facing an issue in my code where I am trying to make one image fade in next to another, regardless of the position of the movable image on the screen. The movable image can be controlled using arrow keys, and when I move it across the screen and spawn the other image with the spacebar, it does not appear as intended. I am unsure whether the problem lies within my style code or jQuery implementation.

Any assistance would be greatly appreciated at your earliest convenience.

jQuery:

$(document).ready(function() {
$('#poop').hide()


$(document).keydown(function(key) {
    switch(parseInt(key.which,10)) {
        case 37:
            $('#ballmer').animate({left: "-=50px"}, 'fast');
        break;
        case 38:
            $('#ballmer').animate({top: "-=50px"}, 'fast');
        break;
        case 39:
            $('#ballmer').animate({left: "+=50px"}, 'fast');
        break;
        case 40:
            $('#ballmer').animate({top: "+=50px"}, 'fast');
        break;
        case 32:
            $('#poop').fadeIn('fast')
        }
    });
});

CSS:

#ballmer{
width:200px;
position:absolute;
margin:0 auto;
padding:0;
border-radius:5px;
}

#poop{
position:relative;
overflow:visible;
}

Answer №1

To manipulate the element within the case 32, it is recommended to utilize jQuery:

JSFIDDLE LINK

Using jQuery and Javascript:

$(document).ready(function () {
    $('#poop').hide()

    $(document).keydown(function (key) {
        switch (parseInt(key.which, 10)) {
        case 37:
            $('#ballmer').animate({
                left: "-=50px"
            }, 'fast');
            break;
        case 38:
            $('#ballmer').animate({
                top: "-=50px"
            }, 'fast');
            break;
        case 39:
            $('#ballmer').animate({
                left: "+=50px"
            }, 'fast');
            break;
        case 40:
            $('#ballmer').animate({
                top: "+=50px"
            }, 'fast');
            break;
        case 32:
            $('#poop').fadeIn('fast');   
            var ball = $("#ballmer");
            var ballmer_top = ball.css("top"); 
            var ballmer_left = subPx(ball.css("left"), ball.width());                 
            $("#poop").css("top", ballmer_top); 
            $("#poop").css("left", ballmer_left);
        }
    });
});

function subPx(a, b) {
    return parseInt(a, 10) - b;
}

Note:

If you want to add an element to the right of the moving one, make the following change:

var ballmer_left = subPx(ball.css("left"), ball.width())
to
var ballmer_left = addPx(ball.css("left"), ball.width())

Include this at the end:

function addPx(a, b) {
    return parseInt(a, 10) + b;
}

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

Using jQuery to combine a variable with the image source in order to replace the image attribute

I am trying to create a script that will display a greeting message to the user based on their local time. I found a script on Stack Overflow, but I am struggling with updating the image source. When I try to replace the image source, I encounter the follo ...

The options for answering (True, False, Yes, and No) are not currently visible

I am struggling with displaying buttons for "True", "False", "Yes", and "No" in an appended row. Here is the application: Application To use the application, follow these steps: 1. Open the application and click on the green plus button. A modal window ...

Opening a fresh window with HTML content extracted from the existing page

Is there a way to open a new window and transfer some of the HTML content from the original page to the new window? For example: $("div#foo").click( function(){ var copyHTML = $("table.bar").html(); window.open(''); // how can we ...

Stacked divs needed to be aligned vertically

Is there a way to make the head and main tabs fixed vertically one below the other? Keep in mind that these need to be separate angular components and cannot be combined under another div. The rows also need to be scrollable. .pages { float: left; ...

Struggling to figure out how to successfully implement the FadeTo method alongside the window scroll event -

I am currently working on a one-page website where I want each section to fade in and out based on the scroll position. Rather than using FadeIn/FadeOut, I am utilizing the FadeTo method to maintain the sections as display:block. The concept is to make ea ...

I am looking to develop a customizable table where the user can input their desired information

Looking to create an HTML page featuring a 10x10 table with alternating red and green squares. After loading the page, a pop-up window will prompt the user to input a word, which will then appear only in the red squares of the table. While I've succes ...

Triggering Submit Button Based on Checkbox Value in jQuery

Hey there, I'm encountering an issue. Let's say I have two types of checkboxes - one for person and one for company. If I submit the form without checking any of the person or company checkboxes, I want jQuery to display an alert. Otherwise, the ...

TypeScript is throwing an error when attempting to extend a type

I am attempting to enhance the jQuery unobtrusive validation interface by adding a new method, but for some reason, it is not recognizing the interface at all. The code snippet below is a simple example I tried running in the TypeScript playground as an ex ...

Utilize jQuery to dynamically add a CSS class to a button

When using jQuery to create dynamic buttons, is there a way to add a CSS class to the button during creation without needing an extra line of JavaScript to add the class afterwards? Below is a example code snippet: $.each(data, function (index, value) { ...

Enhanced spacing of characters in website text

Currently working on a client's website, I find myself once again being asked by my boss (who is the designer) to increase letter-spacing in the text for aesthetic reasons. However, I strongly believe that this practice can actually lead to eye strain ...

Is it expected for every element to return true when checking their visibility with isDisplayed() after performing a get() method

Why are WebDriver get() and isDisplayed() methods not functioning as expected? According to the documentation: This is done using an HTTP GET operation, and the method will block until the load is complete As seen in similar questions such as Wait fo ...

Tips for efficiently webscraping multiple pages with Beautiful Soup

I have been running my web-scraping script for quite some time, but it seems to be stuck on scraping only one URL. I intend to scrape five different URLs, and I am wondering if the issue lies with my loop getting stuck in an infinite loop. Furthermore, I ...

What is the secret behind Redactor JS's ability to display properly indented code snippets?

If you take a look at the Redactor JS demo and click on the button to show the HTML source code of the displayed content... ...you will notice that the code is properly indented: Most rich text editors or wysiwyg editors typically display code in a singl ...

Using Two JavaScript Functions with Identical Names in One HTML File

I am currently facing an issue with a function where the data is retrieved from the getValue() function. The following code snippet is a fragment. grid.js function gridLoadComplete(){ var data = getValue(); } Take into account the following H ...

"Achieving Alignment: Placing a Div Element Inside an H

I am in the process of building a portfolio for freecodecamp, but I am having trouble with centering the button and row div on the page. The row div is necessary because I will be adding more buttons later on, but for now I just need the FCC button. Below ...

Setting the UTF-8 character encoding in Struts2

I am currently working on a JSP file where I collect form values and send them to a Struts 2 action class using jQuery Ajax. Here is what my Ajax function looks like: var DataValues = $("#Form1").serialize(); alert(DataValues); alert(decodeURI(Da ...

Navigating to the most recent item within ng-repeat (AngularJS or JavaScript)

I am working on a feature where posts are displayed using ng-repeat in a div, and users can enter new posts in an input box. The posts are sorted so that the latest one appears at the bottom. After adding a new post, I want to automatically scroll down t ...

Creating a dropdown menu with jQuery

I need assistance in creating a <select> list using jQuery. This is my current attempt: $('<select />') .attr('name', 'location') .val("Location 1") .appendTo(this); Despite setting the value to .val( ...

Implementing a Push System without using node.JS

I am looking to develop a notification system similar to Facebook's, where notifications appear on the bottom-left side of the screen when someone interacts with your posts, for example. However, my challenge is that I need the server to send real-ti ...

The Datatable plugin is unable to effectively customize tables that are loaded dynamically

Within my single page application, the home page initially loads all static resources and js files. Subsequently, upon a user click event, the table is dynamically loaded. Unfortunately, the datatable customization does not seem to be applied on the newly ...