r/JavaScriptHelp • • Jan 05 '22

πŸ’‘ Advice πŸ’‘ hi guys i need your help with this code how to make that "lives--" work properly? p.s I am writing Breakout Game code

1 Upvotes

// you lose 1 live each time fall at bottom

if(ball.getY() + ball.getRadius() > getHeight()){

pause();

ball.setPosition(getWidth()/2, getHeight()/2);

lives--;

if(lives == 0){

stopTimer(draw);

var txt = new Text("Game Over", "30pt Arial");

txt.setPosition(getWidth()/2 - 100, getHeight()/2);

txt.setColor(Color.red);

add(txt);

}

}

r/JavaScriptHelp • • Dec 30 '21

❔ Unanswered ❔ Appending Text fields to email subject line

1 Upvotes

I have a PDF that I'm editing in NitroPDF Pro. There are two text fields in the PDF that I would like to use to compose the subject line. The first text field is labeled Date and the second text field is labeled Time. No matter what I try the file name of the PDF is what is appended to the subject line. I tried using the code below but to no avail. I know nothing about Java Script so any help would be greatly appreciated. Thanks for your time!

var Date = getField("Date").value; var Time = getField("Time").value;

cSubject: "ADVERT: "+Date+" "+Time+"


r/JavaScriptHelp • • Dec 22 '21

❔ Unanswered ❔ Adobe Acrobat Custom Calculation

1 Upvotes

I am creating a fillable rent roll in Acrobat for work and am having trouble with a nuanced calculation. The calculation is based on the number of vacant units in a building and their corresponding square footage. I am wondering if it is possible to write an if-then calculation based on if a check box is filled? If someone has any advice on the best way to write this script, it would be much appreciated. Also, if I am in the wrong place, please point me to a more appropriate community.

Note: I am new to both Acrobat and Java but I have created 85% of the forms I need to and can't finish the rest until I figure out how to write this calculation. I also posted this in r/Acrobat but they don't have many members. (To add context on how little I know: I also posted in r/javahelp not realizing the difference between the language.)


r/JavaScriptHelp • • Dec 20 '21

❔ Unanswered ❔ Help with Jquery click

1 Upvotes

Everything works except the jquery click on the button. The below message comes up?

"Uncaught ReferenceError: JQuery is not defined at eval"

jQuery('#order_refund').click(function () {
    jQuery('#sales_order_view_tabs_order_invoices').click()
    var checkExist = setInterval(function() {
    if (jQuery('a[href*="/sales/order_invoice/view/invoice_id/"]')[0]){
        console.log('Found!');
        clearInterval(checkExist);
        JQuery('a[href*="/sales/order_invoice/view/invoice_id/"]').click();
    } else {
    console.log('Not Found!');
    }
}, 200); // check every 100ms
});

Background

I'm using tamper monkey to check if a link exists, as soon as it appears (Loaded via ajax) it should be clicked automatically.

The code above clicks into the correct section then waits for the loading of the link, console shows the "not found" & "found" which then should click on the link.


r/JavaScriptHelp • • Dec 06 '21

❔ Unanswered ❔ JS/Jquery Radio Button & Text Box Selection

1 Upvotes

I'm very new to JS and am working on a site with code I didn't write, but am trying to correct. Here's how to get to what I'm looking at:

  1. Go to FS Shop

  2. Add anything to your cart and go to to the Checkout Page.

  3. Scroll to the bottom and click the Continue button.

  4. A donation modal will pop up.

    • When you click the text box for the "Enter Amount" option, the radio button is not filled.

    • If you click that radio button, the curser does not move to the text box.

    • If you select one of the other amounts like $50 and then click the text box to enter $5, the radio button for $50 stays filled.

    • You can see that when you click the text box, the associated radio button blinks quickly so something is happening, but not the correct thing.

The 3 main files for this are:

  • checkout.js

  • donation.js

  • jquery-donation.js

When I copy the code from jquery-donation.js to the browser console, it works correctly. However, it doesn't work with the file simply added to the bottom of the page. jquery-donation.js is found, but not working.

There seems to be a conflict or something between this file and checkout.js.

Is anyone able to provide some guidance? I'd be super appreciative to learn how to fix this. TYIA!

Edit: Clarified description


r/JavaScriptHelp • • Nov 20 '21

❔ Unanswered ❔ Error: stuck on loading

1 Upvotes

(https://ibb.co/0QPNBV9) Error message on link


r/JavaScriptHelp • • Oct 22 '21

❔ Unanswered ❔ Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

1 Upvotes

I recently live hosted my website and got this error. Uncaught TypeError: Cannot set properties of null (setting 'innerHTML')

This error did not occur on the local server but it occurred on a public server.

This is the line where the error occurred:

<a onclick="like_post(event)" href="<?= ROOT ?>like/post/<?php echo $ROW['postid'] ?>" style="text-decoration:none;float:left;position:relative;top:2px;">
				<svg id="icon_like" fill="<?= $Like_color ?>" width="22" height="22" viewBox="0 0 24 24">
					<path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z" />
				</svg>
			</a>

This is the JS:

<script type="text/javascript">
		function ajax_send(data, element) {

			var ajax = new XMLHttpRequest();

			ajax.addEventListener('readystatechange', function() {

				if (ajax.readyState == 4 && ajax.status == 200) {

					response(ajax.responseText, element);
				}

			});

			data = JSON.stringify(data);

			ajax.open("post", "<?= ROOT ?>ajax.php", true);
			ajax.send(data);

		}

		function response(result, element) {

			if (result != "") {

				var obj = JSON.parse(result);
				if (typeof obj.action != 'undefined') {

					if (obj.action == 'like_post') {

						var likes = "";

						if (typeof obj.likes != 'undefined') {
							likes =
								(parseInt(obj.likes) > 0) ?
								'<svg fill="#1877f2" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>' :
								'<svg fill="#626a70cf" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>';
							element.innerHTML = likes;
						}

						if (typeof obj.info != 'undefined') {
							var info_element = document.getElementById(obj.id);
							info_element.innerHTML = obj.info;
						}
					}
				}
			}
		}

		function like_post(e) {

			e.preventDefault();
			var link = e.currentTarget.href;

			var data = {};
			data.link = link;
			data.action = "like_post";
			ajax_send(data, e.currentTarget);
		}
	</script>

r/JavaScriptHelp • • Oct 22 '21

❔ Unanswered ❔ How do I solve this uncaught reference error: like_post is not defined at HTMLAnchorElement.onclick?

1 Upvotes

I recently live hosted my website and got this error. Uncaught ReferenceError: like_post is not defined at HTMLAnchorElement.onclick

This error did not occur on the local server but it occurred on a public server. I saw a few threads regarding this error and I heard that you should use addEventListener instead of onclick in your code. However, I'm not sure how to implement it into my code so it would be great if you could help me.

This is the line where the error occurred:

<a onclick="like_post(event)" href="<?= ROOT ?>like/post/<?php echo $ROW['postid'] ?>" style="text-decoration:none;float:left;position:relative;top:2px;">
				<svg id="icon_like" fill="<?= $Like_color ?>" width="22" height="22" viewBox="0 0 24 24">
					<path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z" />
				</svg>
			</a>

This is the JS:

<script type="text/javascript">
     window.onload = function() {
        function ajax_send(data, element) {

            var ajax = new XMLHttpRequest();

            ajax.addEventListener('readystatechange', function() {

                if (ajax.readyState == 4 && ajax.status == 200) {

                    response(ajax.responseText, element);
                }

            });

            data = JSON.stringify(data);

            ajax.open("post", "<?= ROOT ?>ajax.php", true);
            ajax.send(data);

        }
     
        function response(result, element) {

            if (result != "") {

                var obj = JSON.parse(result);
                if (typeof obj.action != 'undefined') {

                    if (obj.action == 'like_post') {

                        var likes = "";

                        if (typeof obj.likes != 'undefined') {
                            likes =
                                (parseInt(obj.likes) > 0) ?
                                '<svg fill="#1877f2" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>' :
                                '<svg fill="#626a70cf" width="22" height="22" viewBox="0 0 24 24"><path d="M21.216 8h-2.216v-1.75l1-3.095v-3.155h-5.246c-2.158 6.369-4.252 9.992-6.754 10v-1h-8v13h8v-1h2l2.507 2h8.461l3.032-2.926v-10.261l-2.784-1.813zm.784 11.225l-1.839 1.775h-6.954l-2.507-2h-2.7v-7c3.781 0 6.727-5.674 8.189-10h1.811v.791l-1 3.095v4.114h3.623l1.377.897v8.328z"/></svg>';
                            element.innerHTML = likes;
                        }

                        if (typeof obj.info != 'undefined') {
                            var info_element = document.getElementById(obj.id);
                            info_element.innerHTML = obj.info;
                        }
                    }
                }
            }
        }
     
        function like_post(e) {

            e.preventDefault();
            var link = e.currentTarget.href;

            var data = {};
            data.link = link;
            data.action = "like_post";
            ajax_send(data, e.currentTarget);
        }
     }
     
    </script>

r/JavaScriptHelp • • Oct 20 '21

βœ”οΈ answered βœ”οΈ Help with getting share-video info to appear

1 Upvotes

This code works on another page, but I’m trying to move it (use it) on a new page. I believe I have copied all that is needed, but it does not display the share-video form. I don’t know a lot about javascript so, I thought I’d start here.

$(function () {
$('#share-video').on('click', function(event) {
      event.preventDefault();
      $('.share-video').toggleClass('hidden');
   });

<div>
<button class="btn-share" id="share-video"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24"><path fill="currentColor" d="M18,16.08C17.24,16.08 16.56,16.38 16.04,16.85L8.91,12.7C8.96,12.47 9,12.24 9,12C9,11.76 8.96,11.53 8.91,11.3L15.96,7.19C16.5,7.69 17.21,8 18,8A3,3 0 0,0 21,5A3,3 0 0,0 18,2A3,3 0 0,0 15,5C15,5.24 15.04,5.47 15.09,5.7L8.04,9.81C7.5,9.31 6.79,9 6,9A3,3 0 0,0 3,12A3,3 0 0,0 6,15C6.79,15 7.5,14.69 8.04,14.19L15.16,18.34C15.11,18.55 15.08,18.77 15.08,19C15.08,20.61 16.39,21.91 18,21.91C19.61,21.91 20.92,20.61 20.92,19A2.92,2.92 0 0,0 18,16.08Z" /></svg> {{LANG share}}</button>
</div>
		  <div class="share-video hidden">
               	  <div class="row share-input">
<div class="col-md-4">
<input type="text" value="{{CONFIG site_url}}/v/<?php echo $pt->get_video->short_id; ?>" class="form-control input-md" readonly onClick="this.select();">
                  </div>
                  </div>
               <a href="#" class="fa fa-facebook" onclick="OpenShareWindow('https://www.facebook.com/sharer/sharer.php?u={{ENCODED_URL}}')"></a>
               <a href="#" class="fa fa-twitter" onclick="OpenShareWindow('https://twitter.com/intent/tweet?url={{ENCODED_URL}}')"></a>
               <a href="#" class="fa fa-google" onclick="OpenShareWindow('https://plus.google.com/share?url={{ENCODED_URL}}')"></a>
               <a href="#" class="fa fa-linkedin" onclick="OpenShareWindow('https://www.linkedin.com/shareArticle?mini=true&url={{ENCODED_URL}}&title={{TITLE}}')"></a>
               <a href="#" class="fa fa-pinterest" onclick="OpenShareWindow('https://pinterest.com/pin/create/button/?url={{ENCODED_URL}}&media={{THUMBNAIL}}')"></a>
               <a href="#" class="fa fa-tumblr" onclick="OpenShareWindow('http://www.tumblr.com/share/link?url={{ENCODED_URL}}')"></a>
               <a href="#" class="fa fa-reddit" onclick="OpenShareWindow('http://www.reddit.com/submit?url={{ENCODED_URL}}')"></a>
               <a href="#" onclick="copyToClipboard(this)" class="fa fa-link" link="{{CONFIG site_url}}/v/<?php echo $pt->get_video->short_id; ?>"></a>
            </div>

Can you make a suggestion as to what I might be missing to get the share links to appear/display?

any help is appreciated


r/JavaScriptHelp • • Oct 18 '21

βœ”οΈ answered βœ”οΈ Dividing a number, then display that result in a form field

1 Upvotes

The form I'd like to modify populates this field (balance amount) upon the page appearing:

<div class="col-md-10">
<input type="text" readonly="true" class="form-control input-md" type="number" placeholder="00" value="{{balance}}">  
</div>

I'd like to divide that balance amount by 2, and have that result display in it's own seperate form field.

Any help with this is appreciated.


r/JavaScriptHelp • • Oct 16 '21

❔ Unanswered ❔ What Java script IDE

1 Upvotes

I'm new to JavaScript having previously only coded in python and I was wondering what are the best free java script IDEs


r/JavaScriptHelp • • Sep 29 '21

βœ”οΈ answered βœ”οΈ Please help

1 Upvotes

I'm very new and know almost nothing. Please help.

https://stackoverflow.com/questions/69383297/javascript-html-im-trying-to-increase-a-value-when-clicking-and-value-retur

^^^(My question)^^^

EDIT: Someone answered the question


r/JavaScriptHelp • • Sep 29 '21

❔ Unanswered ❔ Beginner to JavaScrip - help needed!

1 Upvotes

In the link below, I have a task I am trying to complete and thought I had written the syntax correctly to answer all of the criteria in the task but after I press enter with the pop ups (alerts) for the users input the output is not displayed onto the webpage and I don’t know what I have done wrong, if anyone knows how to fix it I would really appreciate the help!

https://imgur.com/gallery/ZlBc5PL


r/JavaScriptHelp • • Sep 28 '21

❔ Unanswered ❔ How to update the form submit behavior via JavaScript and add a function to open in a new tab?

1 Upvotes

Essentially I have this script from Think Reservations, which takes a bit of html and updates it to create booking widgets according to this documentation. But I cannot for the life of me figure out how to make the link open in a new page. I believe I need to add something to the following chunk of code, but it's way above my head. If anyone could help or even just point me in the direction of some helpful documentation, I'd really appreciate it. Thanks!

key: "handleSubmit",
value: function(t) {
        var e = this;
        t.preventDefault(), this.verifyForm() && ! function() {
                var t = e.props,
                        n = t.shortName,
                        r = t.unitId,
                        i = e.refs.startDateAlt.value,
                        o = e.refs.endDateAlt.value,
                        a = parseInt(e.refs.numberOfAdults.value, 10),
                        u = parseInt(e.refs.numberOfChildren.value, 10),
                        s = [];
                _.times(u, function(t) {
                        var n = parseInt(e.refs["childAge-" + t].value, 10);
                        s.push(n)
                });
                var c = "https://secure.thinkreservations.com/" + n + "/reservations/availability?start_date=" + i + "&end_date=" + o + "&number_of_adults=" + a + "&number_of_children=" + u;
                s.length && (c += "&child_ages=" + s.join(",")), r && (c += "&roomId=" + r), "undefined" != typeof _gaq ? (_gaq.push(["_setAllowLinker", !0]), _gaq.push(["_link", c])) : window.location = c
        }()
}

r/JavaScriptHelp • • Sep 23 '21

❔ Unanswered ❔ Put links on separate lines

1 Upvotes
//below is the array for the list
const links = [
    {
        label: "Week1 notes",
        url: "WDD330/week1/index.html"
    },
    {
        label: "Week2 notes",
        url: "WDD330/week2/index.html"
    }
];

// grabs the ul

const theList = document.querySelector('#wdd330Assign');


// loops through the links array and grabs the label and sets it in the li
for (i = 0; i <= links.length - 1; i++) {
    const li = document.createElement('li');
    //adding the id addLink so I can loop through and add the a tags inside the li
    li.setAttribute('id', 'addLink');
    li.innerText = links[i].label + ': '

    // const a = document.createElement('a')
    // a.setAttribute('href', links[i].url);

    theList.appendChild(li);
}

//grabs the li nested in the ul 
const theLi = document.querySelector('#addLink');

// loops again to add the links to the li element


for (i = 0; i <= links.length - 1; i++){
    const a = document.createElement('a');
    a.setAttribute('href', links[i].url);
    a.innerText = "Click Here";

    theLi.appendChild(a);
}

The code above is supposed to read from the links list and create an li with info about the link and a link. I have the code working but I want it to display the link beside the information of the link. For example:

Info for link: <link goes here>
Info for second link: <new link goes here>

However, I am running into a situation where it is displaying like this:

Info for link: <link goes here><new link goes here>
Info for second link:

Not really sure how to tackle this without creating another loop that gives a new ID each time for the <li> tags. For instance, #addLink1, #addLink2. If you need me to explain more please let me know.


r/JavaScriptHelp • • Sep 04 '21

❔ Unanswered ❔ How do I solve this uncaught DOMException error?

1 Upvotes

I'm currently creating a function where a user can preview an image or video before submit. I did this by making two buttons: one for image files only and the other for video files only. While coding, everything was working fine until I encountered this error in my console:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

This is my HTML so far:

<div class="image-preview" id="imagePreview">
            <img src="" class="image-preview__image">
          </div>

          <div class="video-preview" id="videoPreview">
            <video controls autoplay muted class="video-preview__video" id="video" src=""></video>
          </div>

        <br>
        <label for="inpFile"><img id="image_icon" src="images/images_icon.png"></label>
        <input id="inpFile" type="file" name="file" style="display:none;" accept="image/*">
        <label for="inpFile2"><img id="video_icon" src="images/videos_icon.png"></label>
        <input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*"> 

This is my JS so far:

//preview image in textarea
	const inpFile = document.getElementById("inpFile");
	const previewContainer = document.getElementById("imagePreview");
	const previewImage = previewContainer.querySelector(".image-preview__image");

	inpFile.addEventListener("change", function() {
		const file = this.files[0];

		if(file){
			const reader = new FileReader();

			previewContainer.style.display = "block";
			previewImage.style.display = "block";

			reader.addEventListener("load", function() {
				previewImage.setAttribute("src", this.result);
			});

			reader.readAsDataURL(file);
		}else{
			previewImage.style.display = null;
			previewImage.setAttribute("src","");
		}
	});

  //preview video in textarea
  const inpFile2 = document.getElementById('inpFile2');
  const video = document.getElementById('video');
  const previewVideoContainer = document.getElementById("videoPreview");
  const previewVideo = previewContainer.querySelector(".video-preview__video");
  const videoSource = document.createElement('source');

  inpFile2.addEventListener('change', function() {
    const file = this.files[0];

    if(file){

      const reader = new FileReader();

      previewVideoContainer.style.display = "block";

      reader.onload = function (e) {
        videoSource.setAttribute('src', e.target.result);
        video.appendChild(videoSource);
        video.load();
        video.play();
      };

      reader.onprogress = function (e) {
        console.log('progress: ', Math.round((e.loaded * 100) / e.total));
      };

      reader.readAsDataURL(file);
    }else{
      previewVideo.style.display = null;
			previewVideo.setAttribute("src","");
    }
  });

Any help would be greatly appreciated thanks : )


r/JavaScriptHelp • • Sep 04 '21

❔ Unanswered ❔ How do I solve this uncaught DOMException error?

1 Upvotes

I'm currently creating a function where a user can preview an image or video before submit. I did this by making two buttons: one for image files only and the other for video files only. While coding, everything was working fine until I encountered this error in my console:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

This is my HTML so far:

<div class="image-preview" id="imagePreview">
            <img src="" class="image-preview__image">
          </div>

          <div class="video-preview" id="videoPreview">
            <video controls autoplay muted class="video-preview__video" id="video" src=""></video>
          </div>

        <br>
        <label for="inpFile"><img id="image_icon" src="images/images_icon.png"></label>
        <input id="inpFile" type="file" name="file" style="display:none;" accept="image/*">
        <label for="inpFile2"><img id="video_icon" src="images/videos_icon.png"></label>
        <input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*"> 

This is my JS so far:

//preview image in textarea
	const inpFile = document.getElementById("inpFile");
	const previewContainer = document.getElementById("imagePreview");
	const previewImage = previewContainer.querySelector(".image-preview__image");

	inpFile.addEventListener("change", function() {
		const file = this.files[0];

		if(file){
			const reader = new FileReader();

			previewContainer.style.display = "block";
			previewImage.style.display = "block";

			reader.addEventListener("load", function() {
				previewImage.setAttribute("src", this.result);
			});

			reader.readAsDataURL(file);
		}else{
			previewImage.style.display = null;
			previewImage.setAttribute("src","");
		}
	});

  //preview video in textarea
  const inpFile2 = document.getElementById('inpFile2');
  const video = document.getElementById('video');
  const previewVideoContainer = document.getElementById("videoPreview");
  const previewVideo = previewContainer.querySelector(".video-preview__video");
  const videoSource = document.createElement('source');

  inpFile2.addEventListener('change', function() {
    const file = this.files[0];

    if(file){

      const reader = new FileReader();

      previewVideoContainer.style.display = "block";

      reader.onload = function (e) {
        videoSource.setAttribute('src', e.target.result);
        video.appendChild(videoSource);
        video.load();
        video.play();
      };

      reader.onprogress = function (e) {
        console.log('progress: ', Math.round((e.loaded * 100) / e.total));
      };

      reader.readAsDataURL(file);
    }else{
      previewVideo.style.display = null;
			previewVideo.setAttribute("src","");
    }
  });

Any help would be greatly appreciated thanks : )


r/JavaScriptHelp • • Sep 03 '21

❔ Unanswered ❔ How do I create a code to detect whether a user has selected an image file or a video file?

1 Upvotes

I want to show a preview of an uploaded video file before submit. I have successfully done this with an image thanks to the following JS, but it is not working with video files...

	const inpFile = document.getElementById("inpFile");
	const previewContainer = document.getElementById("imagePreview");
	const previewImage = previewContainer.querySelector(".image-preview__image");

	inpFile.addEventListener("change", function() {
		const file = this.files[0];

		if(file){
			const reader = new FileReader();

			previewContainer.style.display = "block";
			previewImage.style.display = "block";

			reader.addEventListener("load", function() {
				previewImage.setAttribute("src", this.result);
			});

			reader.readAsDataURL(file);
		}else{
			previewImage.style.display = null;
			previewImage.setAttribute("src","");
		}
	});

So I created another JS function for previewing video files before submit:

  const input = document.getElementById('inpFile2');
  const video = document.getElementById('video');
  const previewContainer = document.getElementById("videoPreview");
  const previewVideo = previewContainer.querySelector(".video-preview__video");
  const videoSource = document.createElement('source');

  input.addEventListener('change', function() {
  const files = this.files || [];

  if (!files.length) return;

  const reader = new FileReader();

  reader.onload = function (e) {
    videoSource.setAttribute('src', e.target.result);
    video.appendChild(videoSource);
    video.load();
    video.play();
  };

  reader.onprogress = function (e) {
    console.log('progress: ', Math.round((e.loaded * 100) / e.total));
  };

  reader.readAsDataURL(files[0]);
});

This is my HTML:

  <div class="image-preview" id="imagePreview">
            <img src="" class="image-preview__image" alt="Video selected">
          </div>

          <div class="video-preview" id="videoPreview">
            <video controls autoplay muted class="video-preview__video" id="video" src=""></video>
          </div>

        <br>
        <label for="inpFile"><img id="image_icon" src="images_icon.png"></label>
        <input id="inpFile" type="file" name="file" style="display:none;">
        <label for="inpFile2"><img id="video_icon" src="images/video_icon.png"></label>
        <input id="inpFile2" type="file" name="file" style="display:none;" accept="video/*">
        <input id="post_button" type="submit" value="Post" style="margin:5px;">

I'm not sure how to create a code that can help detect whether the user has selected an image or video file. An example of this feature is used by Twitter. When you select an image/video to tweet, Twitter would let you preview the image/video in the textarea. That's the feature I want to implement into my website. Any help would be greatly appreciated!


r/JavaScriptHelp • • Aug 25 '21

βœ”οΈ answered βœ”οΈ Help with modifying a duration timer display

1 Upvotes

I'm looking for help with tweaking a timer duration which successfully displays upon 'start' and stops successfully upon 'stop'.

However, on the html page , before clicking 'start' this is visible :

And then upon clicking 'start' this displays :

how can I not show : until it all displays?

Also, how can I modify it so that it displays this: 0:00 instead of 00:00 ?

Additionally, how can I delay the timer by 1 second before the timer begins?

Here is the html:

<span id="min"></span>:<span id="sec"></span>

And the js:

var Clock = {
  totalSeconds: 0,
  start: function () {
    if (!this.interval) {
        var self = this;
        function pad(val) { return val > 9 ? val : "0" + val; }
        this.interval = setInterval(function () {
          self.totalSeconds += 1;
          document.getElementById("min").innerHTML = pad(Math.floor(self.totalSeconds / 60 % 60));
          document.getElementById("sec").innerHTML = pad(parseInt(self.totalSeconds % 60));
        }, 1000);
    }
  },
  reset: function () {
    Clock.totalSeconds = null;
    clearInterval(this.interval);
    document.getElementById("min").innerHTML = "00";
    document.getElementById("sec").innerHTML = "00";
    delete this.interval;
  },
  stop: function () {
    clearInterval(this.interval);
    delete this.interval;
  }
};
document.getElementById("start").addEventListener("click", function () { Clock.start(); });
document.getElementById("stop").addEventListener("click", function () { Clock.stop(); });

Any help is appreciated.


r/JavaScriptHelp • • Aug 06 '21

❔ Unanswered ❔ Ball Won't Move! Help?

1 Upvotes

Trying to do my coding homework on khan academy and I'm supposed to make a ping pong type game where the ball bounces around the right side rectangle and it should wobble when it bounces and add a new ball every 30 seconds. It is supposed to start with 5 balls in an array. I am using two other projects I worked on with arrays and having the balls bounce, but neither is giving me the answers. Here is my code (I apologize if im unable to post it this way i just need help!)

I need help with: Getting the ball to move

Showing more than one ball (array of five)

Adding a ball every 30 seconds

var screen = function({)

strokeWeight(3;)

stroke(107, 107, 107;)

fill(179, 179, 179;)

rect(120,1,278,397;//right)

fill(71, 71, 71;)

rect(1,1,119,397;//left)

fill(36, 36, 36;)

rect(1,314,119,84;//score)

fill(255, 0, 0;)

textSize(20;)

text("SCORE",24,321,100,50;)

};

var x = 120; //top

var y = 1;//bottom

var w = 278; //left

var h = 397; //right

var xpos = [];

var ypos = [];

var xspd = [];

var yspd = [];

var cB = [];

var b = 20;

var balls = function({)

for(var i = 0 ; i < 5 ; i++{)

xpos.push(0;)

ypos.push(random(30,370;))

cB.push(color(random(255,random(255,random(255)));))

}

};

var ball = function(x,y,c{)

strokeWeight(1;)

fill(c;)

translate(x,y;)

ellipse(0,0,5,5;)

resetMatrix(;)

};

balls(;)

draw= function( {)

screen(;)

translate(200,200; //Just to see the ball)

for(var i = 0; i < 5 ; i++{)

var x = xpos[i];

var y = ypos[i];

var c = cB[i];

ball(x,y,c;)

xpos += xspd;

ypos += yspd;

xspd = random(-3,3;)

yspd = random(-3,3;)

if(xpos < w + b/2 {)

xpos = w + b/2;

xspd *= -1;

}

if(xpos > h - b/2 {)

xpos = h - b/2;

xspd *= -1;

}

if(ypos < x + b/2 {)

ypos = x + b/2;

yspd *= -1;

}

if(ypos > y - b/2 {)

ypos = y - b/2;

yspd *= -1;

}

}

};


r/JavaScriptHelp • • Aug 05 '21

❔ Unanswered ❔ How to solve filter method retuning undefined?

1 Upvotes

I'm trying to store PurchaseStatus in that products.data. Those products which doesn't have purchase status should be retuned to 0.

Here I'm getting the purchase status, the problem is products which haven't purchased returns undefined in product.data. How can I solve this issue or is there any alternative best solution for this?

I'm new to JS and thanks in advance

products.dataΒ =Β await getAllPurchases().then((purch)Β => products.data.map(inte =>Β {
inte['_purchaseStatus']Β =Β purch.data.filter(pur => pur.ProductIDΒ ===Β inte.id).map(purcha =>
purcha.PurchaseStatus)[0];
return inte;
})).catch(e => console.log(e));


r/JavaScriptHelp • • Jul 30 '21

❔ Unanswered ❔ How do I stop the page from refreshing after submit?

1 Upvotes

I want to create a function similar to live messaging apps where the page does not refresh when a user sends a message. This is my js code so far:

setTimeout(function(){
		messages_holder.scrollTo(0,messages_holder.scrollHeight);
		var message_text = _("message_text");
		message_text.focus();
	},100);

	function send_message(e)
	{
		var message_text = _("message_text");
	}

	function enter_pressed(e)
	{
		if(e.keyCode == 13)
		{
			send_message(e);
		}
	}

This is where I want to include the function in my HTML code:

<input id="message_text" onkeyup="enter_pressed(event)" name="message" placeholder="Type a message...">
														<label for="inpFile"><img id="image_icon" src="http://localhost/mybook/images/images_icon.png" style="left:30px;top:7px;"></label>
														<input id="inpFile" type="file" name="file" style="display:none;" accept="image/*">
 								 						<input id="post_button" type="submit" value="Send" onclick="send_message(event)" style="margin:5px;display:none;">

If you need more information please let me know. Any help would be greatly appreciated!


r/JavaScriptHelp • • Jul 23 '21

❔ Unanswered ❔ How to preview the video file that user wants to upload on the website

1 Upvotes

I want to show a preview of uploaded video file before submit. I have successfully done this with an image thanks to the following JS, but it is not working with video files...

textarea = document.querySelector("#autoresizing");
  textarea.addEventListener('input', autoResize, false);

  function autoResize() {
      this.style.height = 'auto';
      this.style.height = this.scrollHeight + 'px';
  }

  const inpFile = document.getElementById("inpFile");
  const previewContainer = document.getElementById("imagePreview");
  const originalImage = document.getElementById("originalImage");
  const previewImage = previewContainer.querySelector(".image-preview__image");

  inpFile.addEventListener("change", function() {
    const file = this.files[0];

    if (file) {
      const reader = new FileReader();

      previewContainer.style.display = "block";
      previewImage.style.display = "block";
      originalImage.style.display = "none";

      reader.addEventListener("load", function() {
        previewImage.setAttribute("src", this.result);
      });

      reader.readAsDataURL(file);
    }else{
      previewImage.style.display = null;
      previewImage.setAttribute("src","");
    }
  });

r/JavaScriptHelp • • Jul 22 '21

❔ Unanswered ❔ Creating an email signature generator

Thumbnail self.learnjavascript
1 Upvotes

r/JavaScriptHelp • • Jul 13 '21

❔ Unanswered ❔ timeStyle: "short" equivalent that works in all browsers?

1 Upvotes

I have a timestamp like this: 2021-07-23T23:35:00

var myDate = new Date("2021-07-23T23:35:00").toLocaleTimeString("en-US", { timeStyle: "short" }).toLowerCase();

Chrome will give me (correctly):

11:35 pm

IE11 gives me:

β€Ž. 11β€Ž:β€Ž35β€Ž:β€Ž00β€Ž β€Žpm

Safari gives me:

07:35 pm

I've boiled it down to timeStyle: "short".

Is there a way to get this with other toLocaleTimeString options?

Thanks!