Accessing DOMelements generated by Shopify BuyButton.js UI Client

I’m building a website where I want to run a secondary function when the “Add to Cart” button is clicked.

For some reason when I try using any sort of event listener or getElementsbyTagName to access the button created by the BuyButton script, it always returns as undefined and gives me this error:

Uncaught TypeError: Cannot set properties of undefined (setting ‘innerHTML’)

Here’s my code:

   <script src="http://sdks.shopifycdn.com/buy-button/1.0.0/buybutton.js" ></script>    
</head>
<body>
    <div id="shopifyDiv"></div>


    <script type="text/javascript">
    /*<![CDATA[*/
        var client = ShopifyBuy.buildClient({
          domain: 'shopify.myshopify.com',
          storefrontAccessToken: '(myTokenHere)',
        });

        var ui = ShopifyBuy.UI.init(client);

        
        ui.createComponent('product', {
        id: (myIdHere),
        node: document.getElementById('shopifyDiv'),
        options: {
            product:{
              width: '350px',
              contents:{
                img: false,
                button: true,
                title: false
              },
              text: {
          button: 'Add to cart'
        },
            },
          cart:{
            startOpen: false
          },

        }
      
      });


    /*]]>*/
    </script>



  <script type="module">

document.getElementsByTagName('button')[0].innerHTML = 'hello world';

       </script>
    
</body>
</html>

I removed the Shopify specific accessToken & domain name for security purposes.

Any help in understanding why these DOM Elements that are being created by the Shopify script are inaccessible would be highly appreciated.

How i can fix 400 (Bad Request) ajax error on.change form jquery?

Hello guys I have a problem when I’m trying to send data by ajax and it’s said that I have 400 (Bad Request) ajax errors and this is my code:

This is Html code:
the rows is data of my database

 <form id="form">
    <?php foreach($rows as $row): ?>
    <fieldset>
        <?php
          $result_attributes = get_terms([
            'taxonomy' => $row['attribute_woo'],
            'hide_empty' => false,
          ]);
        ?>
        <select id="select-wid" name="<?php echo esc_attr($row['attribute_woo'])?>">
          <option value="">Select</option>
            <?php foreach($result_attributes as $result_attribute) : ?>
                <option value="<?php echo esc_attr($result_attribute->term_id); ?>"><?php echo ($result_attribute->name); ?>
                </option>
            <?php endforeach; ?>
        </select>
    </fieldset>
    <?php endforeach;

This is jquery code:

(function($){
                $(document).ready(function(){
                  $(document).on('change', '#form', function(e) {           

                    var data = $(this).serialize();

                    e.preventDefault();

                    console.log(data);
                    $.ajax({
                      url: my_url,
                      data: data,
                      action: 'myactionfunction',
                      type: 'post',
                      success: function(result) {
                        $('.products').html(result);
                      },
                      error: function(result) {
                        console.warn(result)
                      },
                    });

                  });
                });
})(jQuery);

Wrong result calculation Hour angle from altitude azimuth

I am making a Javascript program and on of the functions is to convert altitude/azimuth to right-ascension/declination given a time and latitude. My code can find the declination fairly accurately, I checked with Stellarium. I have been using this site to help me with the math.

My program gives me the wrong value for horizontal ascension which I plan on using to find right ascension (I already have a function to find local sidereal time which works). Here is my code for the equation
var ha = asin(-sin(az)*cos(alt) / cos(dec)) * (180 / Math.PI); this code is in Javascript but I defined custom sin/cos/asin functions that take degrees as input and return radians because that is the form my data is in.

The site I use also says that this equation should give the same result
var ha = acos((sin(alt) - sin(lat)*sin(dec)) / (cos(lat) * cos(dec))) * (180 / Math.PI);
but, the two equations give different results and neither are correct according to stellarium. I have checked that all the variables I am putting in are correct and I am almost certain I entered the equation correct. Here is the full code on github. I need help figuring out how to fix this problem.
–Note this can be run with node js with no libraries
The result I get is { ra: [ 23, 57, 37.9 ], dec: [ -5, 24, 38.88 ] }
It should be getting { ra: [ 5, 36, 22.6 ], dec: [ -5, 24, 38.88 ] it does not have to be exact, I only really care about the first number of ra (right ascension). It is also formatted in HMS format. The datetime is hardcoded to Febuary 1st 2022 12:00:00 so that is what you should set stellarium to if you are testing this out.

Thank you – CR.

WebRTC Recording Size

After few hours of research I can’t find a solution to my problem and it seems impossible.

I built a simple WebRTC chat (2 clients) where you can create / join a room.

When two clients join the same room they can talk to each other. I have one localStream which is the local user camera and one remoteStream which is the other client camera from the PeerConnection.

I created a button that allows me to start a recording (local) of the remoteStream video. So my client 1 press this button and start record the video of the client 2.

My problem is when I check video data from the remoteStream the frame rate and the video resolution change over time. When I start recording the MediaRecorder grab the current remoteStream size and create a blob which contain my video. Later I can download this video by stopping the recording and download the blob. The problem is the size (definition) of the final video will depend on the current remoteStream size when the user click the button.

So if we are unlucky we will get an entire 360p video for example, if we start the recording later we can have a 1000p video or 868p or other random value between 1p and 2160p. So the video size will depend on the timing and will never be the same.

Is that possible to create a recording which take a fix video size and ignore this WebRTC fluctuation ?

Regards

How do I go about creating a Drag and Drop Grid?

I’ve used Javascript to do a Drag and Drop thing and I found plenty of resources teaching me how to make a sortable drag and drop list, none of them really fit what I need though.

What I’m trying to make though, is a sidebar with 9 items, then have 9 slots I can drag and drop them into displayed as a 3×3 grid. I want to be able to drop them in any available slot, whether it be on the sidebar or the main grid.

I’m absolutely lost on how to even start this, should I be using vanilla JavaScript or something else?

Missing functions in Firebase auth V9

I’m facing a horrible issue with firebase auth. At this point, I’m completely and utterly stumped.

Whenever I try to call user.getIdTokenResult(), I get an error TypeError: undefined is not an object (evaluating 'n.getIdToken').

The user is defined. I log into the console before the function runs, and it always prints out a user. Plus, I’m calling the function in onAuthStateChanged.

What’s even more strange is that it works perfectly on localhost, but once I push to production or even tunnel the domain, it stops working completely.

I have no idea what’s going on.

It looks like this fellow faced the same issue: How to use the getIdToken() auth method in firebase version 9?. No solution, though.

It also looks like it only fails on Safari and iOS.

Code I’m running:

 auth.onAuthStateChanged(async (user) => {
    if (user) {
        console.log('user', user); // prints out a user object
        // Fails here
        const idTokenResult = await user.getIdTokenResult();
...

Claudia Js messenger button custom Reply

I’m a newbie in Claudia Js with lambda and I can’t figure out how to have a custom reply when I click Agree in messenger chat bot then it will show a text then followed by another button
Here is my sample code

module.exports = botBuilder(message => {
if (message.type === ‘facebook’) {
return new fbTemplate.Button(‘Would you like to send your Health Declaration now?’)
.addButton(‘Yes’, ‘YES’)
.addButton(‘No’, ‘NO’)
return new fbTemplate.button(‘By clicking the AGREE button below, you are giving consent to this company.’)
.addButton(‘Agree’, ‘AGREE’)
.addButton(‘Disagree’, ‘DISAGREE’)
.get();
}
});

Thank you for anyone who will answer

Scripting Audacity from Node

I’m attempting to control Audacity® from a Node process using mod-script-pipe.

Their example is in Python, and I would like to port that to Node.

For simplicity, I’d like to get a very basic test working on macOS Catalina.

What I have (ignoring error checking for now):

const os = require('os');
const fs = require('fs');

// Get the current user's identifier (part of the pipe)
const uidText = os.userInfo().uid.toString();
const TONAME = `/tmp/audacity_script_pipe.to.${uidText}`;
const FROMNAME = `/tmp/audacity_script_pipe.from.${uidText}`;
const EOL = "n";
const ENCODING = 'utf-8';

// Omitting the existence checks for brevity

const writeStream = fs.createWriteStream(TONAME, { encoding: ENCODING })

function sendCommand(command) {
  console.log(`Send: >>> ${command}`);
  writeStream.write(command + EOL);
}

sendCommand('Help: Command=Help');

Audacity 3.1.3 is installed and mod-script-pipe is enabled in Audacity preferences. Those pipes exist on my system.

If Audacity is running and I run this script, the script appears to work but Audacity crashes.

The Python script works fine; I suspect my port to Node streams is the issue. Can anyone provide a working example? It doesn’t have to be specific to Audacity if it shows how to port Python streams to Node.

Remove form field javascript

I have a form where I have an table with an employee and every time I click on plus a new row for employee is added but when I click the remove field the script add a new row till the maximum. So what I want is the “-” icon to remove the field added.

This is my code:

<table id="employee_tbl" >
        <tr>
            <th>
                <b><span data-i18n-key="employee">Employee</span></b>
            </th>
        </tr>
        <tr>
            <td>
                <label for="employee"><i class="fas fa-plus-circle"></i></label>
                <input type="text" name="employee"  class="add_button" id="employee" required >
            </td>
        </tr>

and this is the script:

$(document).ready(function(){
          var maxField = 3; //Input fields increment limitation
          var addButton = $('.add_button'); //Add button selector
          var emp = $('#employee_tbl'); //Input field wrapper
          var fieldHTML = '<tr><td><label for="employee"><i class="fas fa-minus-circle"></i></label><input type="text" name="employee" class="remove_button" id="employee" required></td></tr>'; //New input field html 
          var x = 1; //Initial field counter is 1
          
          //Once add button is clicked
          $(addButton).click(function(){
              //Check maximum number of input fields
              if(x < maxField){ 
                  x++; //Increment field counter
                  $(emp).append(fieldHTML); //Add field html
              }
          });
          

           //Once remove button is clicked
           $(emp).on('click', '.remove_button', function(e){
              e.preventDefault();
              $(this).parent('div').remove(); //Remove field html
              x--; //Decrement field counter
          });
          });

Why form element reload the page even if e.preventDefault() is set?

I have a form this I copied from another component, but in this one, it reloads the page even if I set e.preventDefault() in submit function

this is the form field

 <form onSubmit={(e) => handleUpdatePerson(e)}>
                            <input
                              type='text'
                              className='form-control mb-4'
                              placeholder='Name'
                              aria-label='Name'
                              aria-describedby='addon-wrapping'
                              value={name}
                              onChange={(e) => setName(e.target.value)}
                            />
                            <input
                              type='text'
                              className='form-control mb-4'
                              placeholder='Date of Birth'
                              aria-label='Date of Birth'
                              aria-describedby='addon-wrapping'
                              value={dob}
                              onChange={(e) => setDob(e.target.value)}
                            />
                            <input
                              type='text'
                              className='form-control mb-4'
                              placeholder='Gender'
                              aria-label='Gender'
                              aria-describedby='addon-wrapping'
                              value={gender}
                              onChange={(e) => setGender(e.target.value)}
                            />

                            <button className='btn btn-primary w-100'>
                              Update
                            </button>

this is the function

 const handleUpdatePerson = (e) => {
   e.preventDefault();

   console.log('submit fired');
 };

Can’t hide element when empty

<div id="url" class="infoline">
  <i class="fa fa-link fa-2x fa-fw coloriconfa"></i>
  <a href="<?=$data['post']['url']?>" target="_blank"><?=$data['post']['url']?></a>                     
</div>

Hide searches with this function JS

$(document).ready(function() {
$("#url").each(function() {

    if($.trim($(this).html()).length == '') {
       $(this).hide();
    };
 });
});

Help me please

correctly synchronise function operations in a React hook

Consider the following code inside a React custom hook:

function createFadeOut() {
    if (!isDown && fading) {
      if (lineQueue.length !== 0)
        fadeOut(lineQueue.shift());
      else
        addLine(line => { return []; });
    }
    if (isDown && fading) {
      console.log('DOWN!');
    }
  }
  function fadeOut(line) {
      //code 
    }
  }


setInterval(createFadeOut, 60);

So what I want is a set of actions to happen in a discrete interval of time, depending on the state of the mouse and another event. isDown is set when mouse events are called. fading is a boolean state that is just called on a button click.

The specific behavior is that a list pops off an element and calls a function every 60 frames when the mouse is up, AND the list and other actions will be reset if the mouse is ever pressed again.

Of course, I am struggling correctly setting up the behavior.

  • isDown doesn’t represent the mouse state at all when calling the function by a setInterval. Most of the time, it will always be set to true when I already left the mouse alone.
  • Using a useEffect hook, so it always represents the actual state of the mouse is problematic, it will be only called when a render happens and not at an interval.
  • Same problems if I just stick the function in the mouse events and use setTimeouts, especially due to mouseUp only being called on a few frames.

should I continue in .NET or should I choose MERN [closed]

I am 22 year old working as a .NET developer in a product based company. I want to make my career in full stack development. as I am working now on .NET should I continue this and make a career in development using .NET or should I switch to another technology like MERN/MEAN? which would be more helpful for me for the future. If there are any other technologies that have a more brighter future what are they? can anyone pls give me some suggestions regarding the scope of the technologies that I have mentioned above and also pls let me know if there are any other technologies which have a very good future. Thanks!

How to get key value pairs from array of objects using React.js map?

I have just started learning to React, I want to get key:value pairs from array of object using a map loop, The result should look like this qty:1, How can I achieve this result?

import React, { useState } from 'react';
import '../App.css'
const Baseexamplebox = () => {
    return (
        <div style={{marginTop:'30px'}}>
            {variations.map((variant, i)=>(
                    <>
                       <div>{key}:{value}</div>
                    </>
              ))}
        </div>
    );
}

export default Baseexamplebox;


const variations = [
          {
              qty: 1,
              cond: 'Original',
              grade: '',
              comment: '',
              warranty: null,
              price: null
          }
     ]