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

Electron fails to display images in the compiled version

I'm currently troubleshooting an issue related to displaying images using CSS in my electron project. In the latest version of the application, the images are not showing up when linked from a CSS file. However, in a previous version, the images disp ...

Ways to stop two JavaScript files from running at the same time

After combining two JavaScript files, I am facing some issues. The first file handles validation while the second one has an ajax plugin for form submission after validation. When I include these files in the header section, they both run simultaneously. H ...

Bootstrap Modal for WooCommerce

I'm facing an issue while trying to create a modal window using woocommerce variables ($product). The problem lies in the placement of my modal and accessing the correct product id. Here is the code snippet I've been working on. Unfortunately, i ...

Run JavaScript when ColdFusion page is being loaded

Within my ColdFusion page, I have incorporated multiple cfinclude template calls to bring in separate files. Before each cfinclude template call, I am seeking a way to update a javascript variable. I have attempted to achieve this by using: <script typ ...

Display or conceal a field depending on the user's input

I need to display a checkbox only when the firstname matches abc or if the email is [email protected]. var x = abc; //will be dynamic var y = abc @gmail.com jQuery("#firstname").on('change', (function(avalue) { return function(e) { ...

What is the best way to have dual backgrounds displayed on a single webpage?

Looking to recreate the background design featured on this website: www.zucoffee.com. Does anyone have any tips? In addition, I'm curious about how to achieve that curved separation effect. I understand it involves two divs, but how did they manage t ...

Auto play feature malfunctioning in Onsen-UI Carousel attribute settings

When utilizing onsen UI in my mobile web application, I encountered an issue with the autoplay property not functioning properly within the carousel. <ons-page> <ons-toolbar> <div class="left"> <ons-toolbar-button on ...

Adjust the wait time for sliding on the jQuery rcarousel

I am currently utilizing rcarousel for my website and I would like to adjust the duration of time that each slide is displayed. At the moment, each slide stays up for just a few seconds, but I want to extend this so that each slide remains on screen for at ...

Customize a jQuery image slider with varying image widths for a unique touch

I am working on a project to create an image slider with specific requirements: - Infinite loop - Two rows - When the next or previous button is clicked, the slider should move by the width of the upcoming image. Below is a snippet of my HTML: <div c ...

Clearing hoverIntent using jQuery

In my scenario, I have three items identified as X, Y, and Z. The functionality of hovering is controlled by the hoverIntent. When I hover on item X, a tooltip is displayed using the following code: jQuery('.tooltiper').hoverIntent({ ove ...

Ensure at least one checkbox is selected by using jQuery validation

I wrote the code below to select multiple checkboxes and validate that at least one checkbox is selected. The data submission to the database works if I remove onsubmit="return validate_form()". However, I want to ensure that at least one checkbox is selec ...

Ways to customize decoration in Material UI TextField

Struggling to adjust the default 14px padding-left applied by startAdornment in order to make the adornment occupy half of the TextField. Having trouble styling the startAdornment overall. Attempts to style the div itself have been partially successful, b ...

I am sometimes experiencing issues with activating ajax code using Bootstrap 3 modal

I'm stumped trying to find a solution for this issue. Currently, I am utilizing the bootstrap modal to retrieve ajax content from a specified URL. To prevent content overlap, I am using $.removeData() when reloading the content. The problem arises w ...

When deployed, Angular 14 and Bootsrap 5 are functioning properly on a local environment but encountering issues on an online

My Angular application (version 14.2.0) is integrated with bootstrap (version 5.2.3). Upon building and deploying the application on a local IIS server, everything displays correctly as shown in the image below: https://i.sstatic.net/pLDs6.jpg However, w ...

Rails javascript not triggering even after the page is loaded with `page:load`

My experience with using Stripe in Rails has been smooth, except for some issues with Ajax calls not working properly after page refresh. I suspect this might be related to Turbolinks as the 'ready page:load' event doesn't behave as expected ...

Combining an image and a card in Bootstrap 5: a step-by-step guide

Is there a way I can align an image and a card in the same line like in this example? I want the image and card to be combined in one line, but when the page is viewed on mobile devices such as Android or iOS, I want the image to appear at the top with th ...

Understanding the integration of sass with webpack in an Angular 4 project

Is it possible to reference a sass file instead of a css file directly in the index.html? If so, how does webpack compile the sass into a css file? Additionally, what is the most effective way to bundle the sass file when building the application? The ve ...

Retrieving the chosen option using a change event listener

Is there a way to retrieve the selected option using a change listener in TypeScript? I have come across JavaScript examples where the value is retrieved through event., but I am unable to locate any field that contains the selected option. <!DOCTYPE ...

Angular: Radio button groups are not responding correctly when populated within a loop using ng-repeat

My goal is to populate multiple sets of radio buttons in a loop by combining the group name and index to ensure each set is uniquely grouped. However, I am facing an issue where only the last group in the loop has a checked radio button, while all other gr ...

"Scrolling with Bootstrap Scroll Spy is causing incorrect sections to be

Can anyone help me with my issue regarding Bootstrap scrollspy settings? It seems to be highlighting the wrong div id, always the last one. Here is the code snippet: Content: <body style="heigt: 100%" data-spy="scroll" data-target="#side-menu"> ...