javascript if condition not executing properly

I am struggling with my random number generator that should generate numbers between 5 and 15. I am trying to change the position of the 'chest' div based on the number generated by the computer, but for some reason it is not working as expected. I have double-checked that the div is named 'chest', there is a CSS statement for 'left', and the function is indeed being called and generating a number.

Below is the code snippet:


var xChestPosition;
var yChestPosition;
function randomNumberForChest(firstNum, secondNum) {
    xChestPosition = Math.floor(Math.random() * secondNum) + firstNum;
    yChestPosition = Math.floor(Math.random() * secondNum) + firstNum;
    alert(xChestPosition);
    
    switch (xChestPosition) {
        case 5:
        case 6:
        case 7:
        case 8:
        case 9:
        case 10:
        case 11:
        case 12:
        case 13:
        case 14:
        case 15:
            $('#chest').css('left','300');
            break;
        default:
            // Handle other cases
            break;
    }
}

Answer №1

To ensure accuracy in CSS positioning, it is advisable to always specify the unit of measurement.

$('#chessboard').css('left', '300px')

Answer №2

It is suggested to utilize the following code snippet for optimal results:

$('#chest').css({"position": "absolute", "left": "300px"});

Instead of using:

$('#chest').css('left','300');

This is because specifying the position attribute is crucial when setting the left attribute, whether it's absolute, fixed, or relative. By doing so, your conditional statement will be executed accurately.

Answer №3

Give this code snippet a try:

let xPositionOfTreasure;
    let yPositionOfTreasure;

    function generateRandomPositionForTreasure(minNum, maxNum) {
        xPositionOfTreasure = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;
        yPositionOfTreasure = Math.floor(Math.random() * (maxNum - minNum + 1)) + minNum;
        
        alert(xPositionOfTreasure);
        
        switch (xPositionOfTreasure) {
            case 5:
            case 6:
            case 7:
            case 8:
            case 9:
            case 10:
            case 11:
            case 12:
            case 13:
            case 14:
            case 15:
                $('#chest').css('left', '300px');
                break;
            default:
                // Do something else
        }
    }

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

Having trouble with Ajax retrieving the updated JSON file version

I'm pretty new to coding and terminology in general, so I've done my best to simplify my code, although it might still have redundancies. Appreciate your patience in advance. My task involves using an ajax and php script to write data to a file ...

Guide to scraping a website using node.js, ASP, and AJAX

I am currently facing an issue where I need to perform web scraping on this specific webpage form. This webpage is dedicated to vehicle technical reviews, and you can try inputting the car license CDSR70 for testing purposes. As mentioned earlier, I am u ...

How to handle the discrepancy between NextJS exporting files with a .html extension, yet in the <Link> component there is no .html specified

I have been working on my NextJS application and I've realized that all the links within it are built using the <Link href="/my-page"><a>My page</a></Link> component. After exporting the app to generate a static site, ...

What methods can Cypress use to validate content containing hyperlinks?

My current task is to develop an automation test that confirms the presence/display of content containing a hyperlink embedded within text. Please refer to the screenshot I have provided for better understanding, as it illustrates the specific content encl ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

Can Jquery be utilized to signal a language change?

I'm working on my portfolio website that will be available in two languages, Thai and English. I have successfully implemented language buttons for changing between the two languages. However, I am facing an issue with the language selection when nav ...

Successfully passing props to the image source using React/Next.js

Currently, in my implementation with React and Next.js, I am utilizing next-images for importing images. I am looking for a solution to pass data directly to the img src attribute, like so: <img src={require(`../src/image/${data}`)} /> It appears t ...

Adding a half circle connector in HTML can be accomplished by using SVG (Scal

My task is to replicate the construction shown in this image: I have written the entire code but I am unsure how to include a half circle next to the full circle and connect it with a line connector. Here is my code: .ps-timeline-sec { position: rela ...

Tips for expanding third-party classes in a versatile manner using Typescript

tl;dr: Seeking a better way to extend 3rd-party lib's class in JavaScript. Imagine having a library that defines a basic entity called Animal: class Animal { type: string; } Now, you want to create specific instances like a dog and a cat: const ...

On the second attempt, Firefox is able to drag the div element smoothly by itself

I have created a slider resembling volume controls for players using jQuery. However, I am facing an issue ONLY IN FIREFOX. When I drag the slider for the second time, the browser itself drags the div as if dragging images. The problem disappears if I clic ...

Linking HTML files across different directories

Here is the current structure of my folders: de/ index.html en/ index.html hu/ index.html img/ image.png style/ stylesheet.css I am wondering how I can link to the css file in the style folder and the image in the img folder directly ...

Integrate HTML code from one file into another HTML file

I have a specific task in mind: I want to incorporate a header and footer from an external HTML file into another HTML file. Although there are numerous code snippets available here, I'm facing some challenges: Issue: I am unable to modify the exte ...

JavaScript: Collection of Pictures

I've recently begun my journey into HTML and JavaScript by working on a basic website that showcases four images using a for loop. However, upon viewing the website in a browser, I noticed that only the names of the images are displayed, not the actua ...

Iterate over the table data and present it in the form of a Google

I'm struggling to extract data from a table and display it in a google chart. I need some guidance on how to properly loop through the information. HTML <tr> <th>Date</th> <th>Score</th> <th>Result< ...

Tips for transforming a string into an object using AngularJS

Here is a string I'm working with: $scope.text = '"{\"firstName\":\"John\",\"age\":454 }"'; I am trying to convert it into a JavaScript object: $scope.tmp = {"firstName":"John","age":454 }; Please note: J ...

Github not recognizing CSS styles

Currently working on a website to showcase the games I've developed, but encountering issues with applying my CSS. The code can be found here. As a novice in HTML and CSS coding, I've tried numerous codes and tutorials without success. ...

AngularJS users are experiencing issues with the "See More" feature not functioning as expected

One of my tasks involves dealing with a block of text that needs to be truncated using ellipsis. To achieve this, I am utilizing jquery dotdotdot. For more information on dotdotdot, please refer to the documentation. I have created a straightforward dire ...

The values obtained from the previous parameter object of the React setState hook can vary and are not always

In my code, I am using a useEffect hook to update the state with setState. However, I'm encountering some unusual and inconsistent behavior with the previous parameter: useEffect(() => { setCurrentPicturesObject((existing) => { ...

Leverage variable as an expression when utilizing ng-include

Here is an example of working code: <div ng-include src="'Test.html'"></div> However, this code does not work: <div ng-include src="ctrl.URL"></div> (When ctrl.URL is set to "Test.html"). I have also tried setting it t ...

Saving URLSearchParams to a file using javascript

I am currently implementing jstree and I need to be able to click on a file within the tree structure in order to display a PDF file. Below is the relevant code snippet: $(function () { $('#tree').jstree({ 'core' : { ...