CSS Rotation controlled by scrolling speed with jQuery

I’m trying to rotate two objects by scrolling horizontally. The scrolling is controlled by the mousemovement. When the pointer goes right, the objects rotate left, and the other way round. The faster the mouse moves, the more the object rotates.
When the mouse pointer stops for 30ms I want the object to commute slowly with a keyframe that is defined by the current mouse/scroll-speed.
The rotation during the scrolling works fine, but when I added the keyFrame-Function to commute the object, it all went weird.
It starts to rotate after I stop the mouse and it rotates up to 3 times and not in the shortest way.

Maybe someone knows why that is and how to dissolve this problem?

<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Rotating Objects</title>

  <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src='scripts/jquery.keyframes.js'></script>
  <script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>
  <style>
  body {
    overflow: hidden; /* Hide scrollbars */
  }

  .draggable, #draggable2 { 
    border: 2px solid #000; 
    width: 100px; 
    height: 200px;
  }
  #containment-wrapper { 
    width: 400px; 
    height:400px; 
    border:2px solid #000;
    left: 10%; 
    bottom: 10px; 
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  #containment-wrapper_2 { 
    width: 400px; 
    height:400px; 
    border:2px solid #000; 
    left: 30%; 
    bottom: 10px; 
    position: absolute;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  #stage { 
    width: 400vh; 
    height:80vh; 
    border: 1px solid #000; 
    position: relative; 
  }
  </style>
  <script>

  $(document).ready(function() {

  var supportedFlag = $.keyframe.isSupported();

  //set CSS Rotation Degree
  function setRotationDegree(obj, angle) {
    obj.css({
      '-moz-transform' : 'rotate(' + angle + 'deg)',
      '-ms-transform' : 'rotate(' + angle + 'deg)',
      '-o-transform' : 'rotate(' + angle + 'deg)',
      'transform' : 'rotate(' + angle + 'deg)',
      'transition' : 'transform .3s ease-in'
    });
  }

  //set Keyframe Values for commute after stop
  function setRotateKeyframes(keyName, angle) { 
      //angle = angle * -1;
      $.keyframe.define([{
        name: keyName,
        '0%': {'-moz-transform' : 'rotate(' + angle + 'deg)',
                '-ms-transform': 'rotate(' + angle + 'deg)',
                '-o-transform' : 'rotate(' + angle + 'deg)',
                'transform' : 'rotate(' + angle + 'deg)'
              },
        '25%': {'-moz-transform' : 'rotate(' + (angle * -0.9) + 'deg)',
                '-ms-transform': 'rotate(' + (angle * -0.9) + 'deg)',
                '-o-transform' : 'rotate(' + (angle * -0.9) + 'deg)',
                'transform' : 'rotate(' + (angle * -0.9) + 'deg)'
              },
        '50%': {'-moz-transform' : 'rotate(' + (angle * 0.25) + 'deg)',
                '-ms-transform': 'rotate(' + (angle * 0.25) + 'deg)',
                '-o-transform' : 'rotate(' + (angle * 0.25) + 'deg)',
                'transform' : 'rotate(' + (angle * 0.25) + 'deg)'
              },
        '75%': {'-moz-transform' : 'rotate(' + (angle * -0.1) + 'deg)',
                '-ms-transform': 'rotate(' + (angle * -0.1) + 'deg)',
                '-o-transform' : 'rotate(' + (angle * -0.1) + 'deg)',
                'transform' : 'rotate(' + (angle * -0.1) + 'deg)'
              },
        '100%': {'-moz-transform' : 'rotate(0deg)',
                '-ms-transform': 'rotate(0deg)',
                '-o-transform' : 'rotate(0deg)',
                'transform' : 'rotate(0deg)'
              }
      }]);
    }

    var docWidth = $('body').width(),
    slidesWidth = $('#stage').width(),
    rangeX = slidesWidth - docWidth,
    $div = $('#stage');

    $(window).on('resize', function() {
      var docWidth = $('body').width(),
      slidesWidth = $('#stage').width(),
      rangeX = slidesWidth - docWidth;
    })
  
    //variable for if mouse-doesnt-move check
    var timeout = null;

    //variable for scrolling direction check
    var lastScrollLeft = 0;

    $(document).mousemove(function(e) {
      var mouseX = e.pageX,
        percentMouse = mouseX / docWidth,
        offset = percentMouse * slidesWidth - percentMouse * docWidth;

      //check if left or right direction
      var sl = offset;
      var leftOrRight = 0;
      //speed of mousemovement
      var scrollSpeed = offset - lastScrollLeft;

      //Maximum 180degree rotate not necessary?
      scrollSpeed = (scrollSpeed * -30);

      setRotationDegree($('.draggable'), scrollSpeed);

      lastScrollLeft = sl;

      //Rotate back when mouse didn't move for 30ms
      clearTimeout(timeout);

      timeout = setTimeout(function() {
        //setRotationDegree($('.draggable'), 0);

        //THIS BRINGS THE TROUBLE
        setRotateKeyframes('swingRotate', (scrollSpeed));
        $('.draggable').playKeyframe(
          'swingRotate 3s ease-in-out both',
        );
      }, 30);

      $div.css({
        '-webkit-transform': 'translate3d(' + -offset + 'px,0,0)',
        'transform': 'translate3d(' + -offset + 'px,0,0)'
      });
    });

    //Object draggable
    $( ".draggable" ).draggable({ 
      revert: true,
      containment: "#containment-wrapper",
    });
    $( "#draggable2" ).draggable({ 
      revert: true,
      containment: "#containment-wrapper_2",
    });

  });

  </script>
</head>
<body>
<div id="stage">
  <div id="containment-wrapper">
    <div id="draggable" class="draggable">
      <p id="distance"></p>
    </div>
  </div>

  <div id="containment-wrapper_2">
    <div id="draggable2" class="draggable">
      <p id="distance"></p>
    </div>
  </div>
</div>
 
</body>
</html>

Different CSS styles for each HTML tab

Developing a website using Django (irrelevant, really), and have been toying with the implementation of tabs versus a navbar, as I want certain pages to update when selected without completely redirecting to a new page, or refreshing it entirely. For this to be useful, however, each tab would require its own format of CSS, as each page that’s being displayed is inherently different from every other (lets say there are 4 tabs, each tab would display completely different page, ranging from an image library to just text); my question is, how would this theoretically be done, as I have found very little documentation on the matter, other than people claiming “its possible” when asked.

<div class="wrapper">
  <div class="tabs">
    <div class="tab">
      <input type="radio" name="css-tabs" id="tab-1" checked class="tab-switch">
      <label for="tab-1" class="tab-label">Tab One</label>
      <div class="tab-content">sample text</div>
    </div>

Based on the input above, I would assume you could list multiple entries and modify each one using the id=”tab-1″ modifier within CSS, something similar to .tab-1, .tab-2, .tab-3, to update each selection individually, however, this does not seem to work when attempted. I have also attempted to incorporate separate CSS files, which would be the optimal result, however, they do not seem to load properly when incorporated, and I have found little documentation on implementing multiple CSS files in the way that is required for differential tabs.

(Alternatively, is there a way to obtain this format using a navbar, whereas instead of a link to a separate page, it displays the change within the body, similar to a tab modifying its container; ultimately, I want the display to be similar to that of a navbar.)

Thanks for your help.

Puppeteer / POST Request

I’m trying now since over 48 hours and googelt almost the whole web. My problem is that when use puppeteer the POST Request is not working – I tried many websites but the POST Form Action is not working. Can somebody help me?

File test.js
Usage: node test.js

const puppeteer = require('puppeteer');
const randomUseragent = require('random-useragent');
const USER_AGENT = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.36';

(async () => { const browser = await puppeteer.launch({ args: ['--no-sandbox'] }) // headless: true,

const page = await browser.newPage()
    
await page.setViewport({
    width: 1920 + Math.floor(Math.random() * 100),
    height: 3000 + Math.floor(Math.random() * 100),
    deviceScaleFactor: 1,
    hasTouch: false,
    isLandscape: false,
    isMobile: false,
});

const userAgent = randomUseragent.getRandom();
const UA = userAgent || USER_AGENT;

await page.setUserAgent(UA);
await page.setJavaScriptEnabled(true);
await page.setDefaultNavigationTimeout(0);

await page.setRequestInterception(true);
page.on("request", interceptedRequest => {

        var data = {
            
            "method": "POST",
            "postData": "URLz=VIDEOURL"
        };
        interceptedRequest.continue(data);
    });
    
const response = await page.goto('https://fdown.net/download.php')
 //const responseBody = await response.text();
 
await page.screenshot({ path: 'affe.png', fullPage: true })
await browser.close()

})()

TypeError: this.cliEngineCtor is not a constructor

I’m running a react app using a yarn package manager. I’m getting the aforementioned ESLint error. I have tried the following to fix it:

  1. Deleted package-lock.json and node modules and installed yarn and ran yarn init
  2. Modified the eslint-plugin.js file to include at the top of the file:

I used both of these at different times to no avail:

   this.CliEngineCtor = require(this.basicPath).CLIEngine;
   this.CliEngineCtor = require(this.basicPath).CLIEngineCtor;

Pertinent package.json entry:

{
  "name": "react-millionaire-quiz",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.1",
    "@testing-library/react": "^12.1.2",
    "@testing-library/user-event": "^13.5.0",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "^5.0.0",
    "web-vitals": "^2.1.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "eslint": "^8.7.0"
  },

I tried changing the eslint to lower versions, but that just created other problems breaking other dependencies and creating other errors.

How can this be fixed, or do I have to disable ESLint?

Loop is not incrementing

I am new to javascript.

I have to create a function that returns the next multiples of 5 based on a given number.But my loop repeats the information, it doesn´t increment the result.What am I doing wrong?

function proS (num, mult){
    let arr = []

for (var i = 1; i <= mult; i ++){
arr.push(Math.ceil(num / 5) * 5)
}
return arr
}

proS(6,4)

returns [10,10,10,10]

Execution Timed Out (12000 ms): How can I optimize JS kata to run faster? [Upside-Down Numbers – Challenge Edition]

    function upsideDown(x, y) {
      const list = ["0", "1", "6", "8", "9"];
      let count = 0;
      for (let i = parseInt(x); i <= parseInt(y); i++) {
        let curr = i.toString().split("");
        let upsideDownCurr = "";
        if (
          !curr.every(function (x) {
            return list.includes(x);
          })
        )
          continue; // Skips if number includes non-upDown num
        for (let j = 0; j < curr.length; j++)
          if (curr[j] === "6") upsideDownCurr = "9" + upsideDownCurr;
          else if (curr[j] === "9") upsideDownCurr = "6" + upsideDownCurr;
          else upsideDownCurr = `${curr[j]}` + upsideDownCurr;
        if (upsideDownCurr === curr.join("")) count++;
      }
      return count;
    }

Input:

Your function will receive two strings, each comprised of digits representing a positive integer. These two values will represent the upper and lower bounds of a range.
Output:

Your function must return the number of valid upside down numbers within the range of the two input arguments, including both upper and lower bounds.
What is an Upside-Down Number?

An upside down number is an integer that appears the same when rotated 180 degrees, as illustrated below.

This works fine untill
Test.assertEquals(upsideDown('100000','12345678900000000'),718650)
any idea how to optimize the code?

addEventListener: click just one element of a bunch of elements

I’m beginner and have trouble with something in JS that might be simple to solve.

I made a quiz based on a NetNinja Udemy course, and I want the submit button to be enabled just when the user clicks on any answer option, and not before, so that he/she can’t send a totally empty quiz.

The quiz has 4 questions with 2 options each, and I found this way…

const input_a = document.getElementById("q1a");
const input_b = document.getElementById("q1b");


button.disabled = true;




input_a.addEventListener('click', () => {
    button.disabled = false;

});

input_b.addEventListener('click', () => {
    button.disabled = false;

});

…to enable the button when the user clicks on any of the two options of the first question (ids: q1a & q1b) Following this logic, there’d also be q2a, q2b, q3a, q3b, q4a & q4b..

As there is a way to include all the answers in one JS element, what should I do in the event function to say “when you click any of this 8 options, enable the button”? Because everything I tried only makes the function work if I click all the buttons, which is obviously impossible in a Quiz .

Thank you! 🙂

Regex for ISO8601 temporal duration but only with minutes and seconds

I’m attempting to write Regex to match the ISO8601 standard for temporal durations, but only where PT and M or S are valid.

So far I have found a full example of ISO8601 regex but it is more complex than I need. I need match durations like the following:

  • PT7S
  • PT10M50S
  • PT150S

Essentially I want the Regex to always check that:

  • capitalised PT is at the beginning of the string
  • M is preceded by a whole number
  • S is preceded by a whole number
  • M comes before S

My attempt so far:

  • capitalised PT at the beginning = ^PT
  • M preceded by a whole number = [0-9]+M – except this allows something like 10.5M because the 5M counts
  • S preceded by a whole number = same as above
  • M comes before S. Again no idea!

I’m really stuck on trying to figure this out, I’ve been trying to get each part to match so I could try and combine them all later but I can’t get over the first hurdle.

d3.js visualisation won’t centre on iPhone screen

I am working on a project with d3.js where I want a visualisation to centre on the screen. My current solution works perfectly on desktop screens, even when resizing, but when I load the webpage on my iPhone screen, the visualisation is no longer centred. The target div for this visualisation is:

<div id="grades_circular" class="my_dataviz"></div>

The css to style is:

.my_dataviz {
display: flex;
justify-content: center;}

The JavaScript code for the visualisation is :

const grades_margin = {top: 30, right: 0, bottom: 70, left: 0},
      grades_width = 460 - grades_margin.left - grades_margin.right,
      grades_height = 460 - grades_margin.top - grades_margin.bottom;
      innerRadius = 50,
      outerRadius = Math.min(grades_width, grades_height) / 2;

const grades_svg = d3.select("#grades_circular")
  .append("svg")
    .attr("width", grades_width + grades_margin.left + grades_margin.right)
    .attr("height", grades_height + grades_margin.top + grades_margin.bottom)
  .append("g")
    .attr("transform", `translate(${grades_width/2+grades_margin.left}, ${grades_height/2+grades_margin.top})`);



d3.csv("https://raw.githubusercontent.com/ben-austin27/ben-austin27.github.io/main/data/results.csv").then( function(grades_data) {
  
const grades_x = d3.scaleBand()
      .range([0, 2 * Math.PI])    // X axis goes from 0 to 2pi = all around the circle. If I stop at 1Pi, it will be around a half circle
      .align(0)                  // This does nothing
      .domain(grades_data.map(d => d.module)); // The domain of the X axis is the list of states.

const grades_y = d3.scaleRadial()
      .range([innerRadius, outerRadius])   // Domain will be define later.
      .domain([40, 100]); // Domain of Y is from 0 to the max seen in the data

  // Add the bars
bars = grades_svg.append("g")
    .selectAll("path")
    .data(grades_data)
    .join("path")
      .attr("fill", d => "#" + d.color )
      .attr("d", d3.arc()     // imagine your doing a part of a donut plot
          .innerRadius(innerRadius)
          .outerRadius(innerRadius+0.05)//d => grades_y(d['grade'])
          .startAngle(d => grades_x(d.module))
          .endAngle(d => grades_x(d.module) + grades_x.bandwidth())
          .padAngle(0.05)
          .padRadius(innerRadius))
  
modules = grades_svg.append("g")
      .selectAll("g")
      .data(grades_data)
      .join("g")
        .attr("text-anchor", function(d) { return (grades_x(d.module) + grades_x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "end" : "start"; })
        .attr("transform", function(d) { return "rotate(" + ((grades_x(d.module) + grades_x.bandwidth() / 2) * 180 / Math.PI - 90) + ")"+"translate(" + (innerRadius+10) + ",0)"; })//
      .append("text")
        .text(function(d){return(d.module)})
        .attr("transform", function(d) { return (grades_x(d.module) + grades_x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "rotate(180)" : "rotate(0)"; })
        .style("font-size", "11px")
        .attr("alignment-baseline", "middle")

grades = grades_svg.append("g")
      .selectAll("g")
      .data(grades_data)
      .join("g")
        .attr("text-anchor", function(d) { return (grades_x(d.module) + grades_x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "end" : "start"; })
        .attr("transform", function(d) { return "rotate(" + ((grades_x(d.module) + grades_x.bandwidth() / 2) * 180 / Math.PI - 90) + ")"+"translate(" + (grades_y(d['grade'])+7) + ",0)"; })//
      .append("text")
        .text(function(d){return(d.grade)})
        .attr("transform", function(d) { return (grades_x(d.module) + grades_x.bandwidth() / 2 + Math.PI) % (2 * Math.PI) < Math.PI ? "rotate(180)" : "rotate(0)"; })
        .style("font-size", "11px")
        .attr("alignment-baseline", "middle")

function update_bars() {
  d3.selectAll("path")
      .transition()
      .ease(d3.easePolyInOut.exponent(3)) //https://observablehq.com/@d3/easing-animations
      .duration(2000)  
      .attr("d", d3.arc()     // imagine your doing a part of a donut plot
          .innerRadius(innerRadius)
          .outerRadius(d => grades_y(d['grade']))
          .startAngle(d => grades_x(d.module))
          .endAngle(d => grades_x(d.module) + grades_x.bandwidth())
          .padAngle(0.05)
          .padRadius(innerRadius))
// alter opactity of the labeling as well, after 2 seconds
}

var controller = new ScrollMagic.Controller();
new ScrollMagic.Scene({
  // the element to scroll inside
  triggerElement: '#grades_circular'
})
.on('enter', function(e) {
    update_bars(e);
}).addTo(controller)
});

Thanks!

Uncompress a string

Write a function, uncompress, that takes in a string as an argument.
The input string will be formatted into multiple groups according to
the following pattern:

number + char

for example, ‘2c’ or ‘3a’.

The function should return an uncompressed version of the string where
each ‘char’ of a group is repeated ‘number’ times consecutively. You
may assume that the input string is well-formed according to the
previously mentioned pattern.

test_00: uncompress(“2c3a1t”); // -> ‘ccaaat’

Here is my code which is using a stack. The problem is that it’s only returning ‘cc’ and I can’t figure out why. I’ve console logged what goes into the IF ELSE and I’m hitting both so I don’t understand why nothing gets pushed to the stack.

Would really appreciate the help if someone can spot what I’m missing.

const uncompress = (s) => { 
  const nums = '23456789';
  const stack = []; 
  for (let char of s) {
    if (nums.includes(char)) {
      stack.push(Number(char));
    } else {
      const num = stack.pop();
      stack.push(char.repeat(num));
    };
  };
  return stack.join('');
};

I can’t read the form elements [closed]

I can’t get the values of these three fields; it only returns an empty value (a space).
The ids are correctly set in the form.

Is there a code setting error?

const data = {
  id: document.getElementById('id').value,
  nameBook: document.getElementById('namebook').value,
  priceBook: document.getElementById('pricebook').value
};

How to scrape Yahoo Finance with Cheerio in Javascript?

I’m trying to pull a real time price from Yahoo Finance, based on an old post, and the latest price attribute (data-reactid=”47″) seen in Yahoo Finance. But the following code doesn’t extract the price data. What am I missing? I would appreciate any help. Thank you!

function test() {
  const url = 'https://finance.yahoo.com/quote/AAPL?p=AAPL&.tsrc=fin-srch';
  const res = UrlFetchApp.fetch(url, { muteHttpExceptions: true }).getContentText();
  const $ = Cheerio.load(res);
  var price = $("span[data-reactid='47']").text().toString();
  console.log(price)
}

Item deletion using jquery ajax

Am having a problem with my jquery

i want to delete some products

but the only problem am getting, the deletion works only on first items even if i click the last item

Lets say i want to delete <p>INFO 20002</p> it will delete <p>INFO 2000</p>

i want to be able to delete any item i want

<script>
   function callB() {
    
    $("#button1").click(function(event) {
        Execute();
    });
   
    function Execute() {
        
        $.ajax({
            type: 'POST',
            url: 'ajax/file.aspx',
            data: {
                'custId': $("input[name='custId']").val()
            },
            success: function(response) {
                    
            },
            error: function() {
                alert("error");
            }
        });
    };
   }
   
   $(document).ready(function() {
    callB();
   });
</script>



<div>
<p>INFO 2000</p>
<input type="button" id="button1" value="Erase this">
 <input type="hidden" name="custId" value="348700">
</div>

<div>
<p>INFO 20001</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="4443487">
</div>

<div>
<p>INFO 20002</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="8883487">
</div>

<div>
<p>INFO 20003</p>
<input type="button" id="button1" value="Erase this">
<input type="hidden" name="custId" value="1113487">
</div>