Establishing limits for a division using keyboard commands

Alright, I've decided to remove my code from this post and instead provide a link for you to view it all here:

(please disregard any SQL errors)

  • If you click on a Grid-Node, the character will move to that position with boundaries enabled.
  • Dragging the character will also move it to a new position with boundaries enabled.
  • Using the keyboard cursor keys will move the character without boundaries.

I am looking to establish boundaries of #character to be within #map when using the keyboard - currently the boundaries work only with the mouse movement

Answer №1

It seems like the bounding might be off. I've adjusted all the if statements to ensure that the character stays within the map boundaries.

$(document).bind('keydown',function(e){ //define keydown function...
    switch(e.which) 
        case 37:    $(characterName).css("background-image", "url(img/character-left.gif)");  //pressing LEFT ARROW KEY
                    var character = $(characterName);
                    var map = $('#map');

                    if((character.offset().left - 40) >  map.offset().left) {
                        character.animate(
                            {
                                left: '-=40'
                            },
                            250,
                            function(){}
                        );
                    }
                    break;
        case 39:    $(characterName).css("background-image", "url(img/character-right.gif)"); //pressing RIGHT ARROW KEY
                    var character = $(characterName);
                    var map = $('#map');

                    if((character.offset().right + 40) <  map.offset().right) {
                        character.animate(
                            {
                                left: '+=40'
                            },
                            250,
                            function(){}
                        );
                    }
                    break;
        case 38:    $(characterName).css("background-image", "url(img/character-up.gif)"); //pressing UP ARROW KEY
                    var character = $(characterName);
                    var map = $('#map');

                    if((character.offset().top - 40) <  map.offset().top) {
                        character.animate(
                            {
                                top: '-=40'
                            },
                            250,
                            function(){}
                        );
                    }
                    break;
        case 40:    $(characterName).css("background-image", "url(img/character-down.gif)"); //pressing DOWN ARROW KEY
                    var character = $(characterName);
                    var map = $('#map');

                    if((character.offset().bottom + 40) <  map.offset().bottom) {
                        character.animate(
                            {
                                top: '+=40'
                            },
                            250,
                            function(){}
                        );
                    }
                    break;
    }
});

Answer №2

While I may not be an expert in JQuery, it appears that whenever you use top with a value like '+=40', it seems to have trouble recognizing the "+=" as an operator. It might be better to update the top property by retrieving its current value, adding to it, and then setting it back to top.

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

Issue with the JSON response in MVC 4

I have been struggling to bind JSON values to specific text boxes. It works with dynamically created textboxes but not with static ones that are already present. I've been stuck on this issue for 2 days and despite searching the internet, I couldn&apo ...

CSS Background color only applies to the lower section of the page

I'm attempting to create a social media button using an anchor tag and a fontawesome icon. My goal is to have the entire background colored black with CSS, but my previous attempts only resulted in the bottom half turning black. Html: <div class ...

conceal a targeted section from the bottom of the iframe

I have a website embedded inside an iframe for use in a webview application. <body> <iframe id="iframe" src="http://www.medicamall.com"></iframe> </body> This is the CSS code: body { margin:0; padding:0; height:10 ...

Making jQuery work: Utilizing tag replacements

My current code is: this.html(this.html().replace(/<\/?([i-z]+)[^>]*>/gi, function(match, tag) { return (tag === 'p') ? match : '<p>'; return (tag === '/p') ? match : '</p& ...

Encountering a 404 error when making a basic WCF request through IIS using jQuery

I'm facing an issue that seems to be a common one - I am trying to connect a WCF service hosted on local-IIS with an ASP.NET WebApp also hosted on local-IIS. The web app can successfully access the .svc file from the AJAX call below, but when I add /G ...

Unexpected '->' found on page during loading

After migrating my WordPress site from localhost to the live server, I encountered an issue where "-->" appeared before the page finished loading. Can anyone explain this strange behavior? In addition to this issue, the jQuery scripts I had implemented ...

Tips for successfully passing the event in a jQuery function

I currently have four buttons on my HTML page. Create Airport Create City Create City Shortname Create Airport Shortname All of these buttons will trigger an AJAX call to the same page. Here is a snippet of the code for one of the buttons: $('#im ...

What are the steps for implementing the innerClass style on the searchBox within the appBase?

I'm currently incorporating the searchBox component from appbase io into my upcoming js web application, but I've been facing challenges in customizing the layout of both the search box and the list. Despite following the documentation which sug ...

Vertical centering of inline-block elements remains unaffected by line-height changes

I attempted to center an inline-block vertically in the following manner: div { width: 50px; height: 50px; background: red; line-height: 50px; } span { display: inline-block; width: 20px; height: 20px; background: white; } <div> ...

Refresh the table every couple of seconds

I need to regularly update a table every two to three seconds or in real-time if possible. The current method I tried caused the table to flash constantly, making it difficult to read and straining on the eyes. Would jQuery and Ajax solve this issue? How c ...

Can the system automatically generate and display a new user ID right after a form is submitted?

Once users have submitted the basic information in a form, how can I ensure that the newly created userID is displayed in a hidden field on the header page? The initial form collects Name, Phone, and Email details. Upon submission, the 'userID' ...

Encountering an issue with html2canvas: receiving an error message stating "object

To print the div using Javascript, I encountered an issue with the generated barcode not appearing in the printed page. This led me to use the html2canvas approach to 'render' the div before printing it out. Here is the code snippet: HTML: < ...

Display React elements on the web page

Seeking assistance from anyone! I've been grappling with a problem and can't seem to figure out a solution. Here's the scenario: My current setup involves a sidebar and a top bar for navigation in React. Check out my app so far in this imag ...

Optimal method for incorporating Django with an Ajax framework

When it comes to integrating javascript libraries with a Django application, the options are abundant and diverse. Personally, I am leaning towards utilizing jQuery due to its popularity and robust features, although I am open to exploring other alternativ ...

Blend Image and Text with jQuery when Hovered Over

Alright, so here's the deal - I have an image that needs to smoothly transition to another image when hovered over. I also have some descriptive text that should crossfade into different text corresponding to the second image. The current setup is ki ...

Can CSS blend with elements beyond the stacking context?

I am currently in the process of constructing a "hero area" for my webpage through a CMS. This hero area will feature a background image, text content, and a couple of button links. My goal is to have the buttons utilize the mix-blend-mode:multiply propert ...

"Utilizing jQuery to add new items to a list using the

I'm a bit confused about the distinctions among these four lines of code: $('<li>').addClass('restaurant').appendTo('ul'); $('li').addClass('restaurant').appendTo('ul'); $('li& ...

Encountering a database deletion error with Spring Boot Thymeleaf

I'm currently facing an issue where I am attempting to remove an entry from my database. However, when I try to delete it on my html page, I end up being redirected to an error page instead of the intended destination. The entry I am trying to delete ...

pure-react-carousel: every slide is in view

Issue I am encountering a problem where the non-active slides in my container are not being hidden properly. This results in all of the slides being visible when only one should be displayed. Additionally, some slides are rendering outside of the designate ...

Execute another Ajax request using jQuery after the first Ajax callback has been completed

Looking for a solution to ensure the correct order of appended contents loaded via ajax, I have the following script: $.get('http://mydomain.com/ajax1.php/', function(data){ var data_one = $(data).find('#ajax_editor_suggestion_c ...