How to select individual elements with javascript here? - javascript

See here: https://siteweb.synergieetvitalite.com/monportfolio/
I would like the smartphone and laptop to come close togheter as the user moves his mouse. The code i am using :
HTML:
<div class="scene">
<div data-speed="51" class="layer layer-middle"></div>
<div data-speed="81" class="layer layer-top"></div>
</div>
JS:
<script> document.addEventListener('mousemove', parallax);
function parallax(e) {
e.preventDefault();
this.querySelectorAll('.layer-middle').forEach((layer) => {
let speed = layer.getAttribute('data-speed');
layer.style.transform = `translateX(${e.clientX * speed / 1000}px)`;
})
}
</script>
I tried to modify this so that .layer-top moves to the right, but then the layer-middle stopped moving alltogheter, probablement because of SelectorAll or forEach. I don't really know javascript so I wasn't able to simply make the function work for each element individually.
thanks for your help!

I think you can remove the foreach and select each element separately like below. So this way you will move the laptop to right and the phone to left or vice versa.
I've changed your code a little. Try it and let me know if its what which you are looking for.
<script> document.addEventListener('mousemove', parallax);
function parallax(e) {
e.preventDefault();
laptop = document.querySelector('.layer-middle');
let speed = laptop.getAttribute('data-speed');
laptop.style.transform = `translateX(${e.clientX * speed / 1000}px)`;
phone = document.querySelector('.layer-top');
phone.style.transform = `translateX(${-1*e.clientX * speed / 1000}px)`;
}
</script>

Related

Why's my wheel spinning repugnantly when clicking?

I'd like to know why the wheel spins like a bent bicycle tire when clicking Spin Now. I've tried a lot of ways to try to rectify this so that it spins normally like the Wheel of Fortune wheel but to no avail.
I tried switching up the image, give it a height and width, slow down the wheel but nothing seems to be working and it feels like I'm running out of options
I think my jQuery code is a bit off and is causing this inconsistent behavior but I could be wrong. How can make the wheel spin normally? A JsFiddle (https://jsfiddle.net/hbxL2s8r/26/) and code below is provided for reference.
Here's HTML:
<div id="spin-now" class="buttons">
<img src="https://i.postimg.cc/28JSM5Kf/spin-now-glow-button-NEW.png" alt="">
</div>
<div id="image-spinner" class="text-center">
<img src="https://i.postimg.cc/nzZz2wwj/wheel-no-glow-v03.png"/>
</div>
Here's my jQuery:
var degrees = 0, previousRotation = 0;
var spinNow = document.getElementById('spin-now');
spinNow.addEventListener("click", function (e) {
console.log("triggered");
$('#spin-now').hide();
previousRotation = degrees;
degrees += parseInt(360 * 10 + 315);
// controls speed of wheel
var milliseconds = parseInt((degrees - previousRotation)) * 1.5;
$("#image-spinner").css({
"-webkit-transform" : "rotate("+ degrees +"deg)",
"-webkit-transition-duration" : milliseconds + "ms"
});
});

Connecting the HTML input page with p5.js

I want to get the data from input tags and use them in the equation.
I have tried a lot a lot of solutions, nothing worked.
I want it to start setup after click one button, and start animate after pressing the other button.
press button1
load the data from the html
set up the canvas using those data
execute draw() for ever.
I did not find much documentation.
Here is my html:
<label class="col-lg-2" for="n4" id="m2">mass sq 2</label>
<input class=" col-lg-2" name="n4" type="number" id="m2" label="mass sq 2" />
<label class="col-lg-2" for="n5" id="r">Ratio</label>
<input class="ana col-lg-2" name="n5" type="number" id="r" label="Ratio" />
<button class="col-lg-2 btn btn-danger" style="margin-left: 10%;
height:30px;"> <h3> change </h3> </button>
and here is the p5.js code:
button1 = CreateButton('submit1');
button2 = CreateButton('submit2');
let digits = document.getElementById('m2').Value;
const timeSteps = 10 ** (digits - 1);
let m1 = document.getElementById('m1').Value;
function preload() {
blockImg = loadImage('block.png');
clack = loadSound('clack.wav');
}
function setup() {
button2.mousePressed(start);
}
function draw() {
button2.mousePressed(finish);
}
function start() {
createCanvas(windowWidth, 200);
block1 = new Block(100, 20, m1, 0, 0);
const m2 = pow(100, digits - 1);
block2 = new Block(300, 100, m2, -1 / timeSteps, 20);
countDiv = createDiv(count);
countDiv.style('font-size', '72pt');
}
This answer uses instance mode to create a canvas with width and height set from user inputs. This allows us to call createCanvas() inside of setup. The code only allows us to create one canvas but it would not be hard to modify so that multiply canvases could be created, however, we should never call createCanvas more than once for each instance of p5.
var canvas = null;
function createP5 (){
let canvasWidth = document.getElementById("widthInput").value;
let canvasHeight = document.getElementById("heightInput").value;
if (canvas === null){
canvas = new p5(function (p) {
p.setup = function (){
p.createCanvas(canvasWidth, canvasHeight);
}
p.draw = function(){
p.background(55);
p.stroke(0);
p.rect(p.width/5, p.height/5, p.width/5 * 3, p.height/5 * 3);
}
}, "canvas-div");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/0.7.3/p5.min.js"></script>
<div id="canvas-div">
</div>
<input type="button" value="create canvas" onclick='createP5()'/>
<textarea id="widthInput"></textarea>
<textarea id="heightInput"></textarea>
You're asking a few different questions:
How do I run code when a user presses a button?
There are a few ways to do this, but it sounds like you're looking for the onclick attribute. You can Google "JavaScript onclick" for a ton of resources.
How do I run a P5.js sketch from JavaScript code?
For this, you probably want to use instance mode to have more control over exactly when the sketch is created. See this page for more info.
The best advice I can give you is to start smaller. Start with a simple page that shows a single button that prints something to the console when you click it. Then add a simple P5.js sketch using instance mode. Work forward in small steps instead of trying to do everything all at once.
Good luck.

Javascript - object.offsetTop and .offsetLeft gives 0

I'm trying to get the position of an element by using Javascript. I have used clientTop, offsetHeight, window.getComputedStyle(box1).top and a few things in between but all I get when I console log it is 0. The element is placed almost in the middle of the page so it should be all but 0 in the result.
HTML:
<body>
<h1>Box placement</h1>
<div id='box1' class='box center green size200'>
</div>
</body>
JS:
let box1 = document.querySelector('#box1');
let browserHeight = window.innerHeight;
let browserWidth = window.innerWidth;
let boxHeight = box1.clientTop;
let boxWidth = box1.offsetLeft;
function printInfo() { //Result
console.log(browserHeight); //1185
console.log(browserWidth); //1266
console.log(boxHeight); //0
console.log(boxWidth); //0
console.log(window.getComputedStyle(box1).top); //auto
console.log(box1.offsetLeft); //0
}
printInfo();
Any ideas to where I might have gone wrong? Here is a fiddle with the CSS as well: http://jsfiddle.net/1f23v9nj/1/
That behaviour is caused by the less.js library. If you don't really need its features, then don't include it -- problem solved.
If you do need it -- for reasons not apparent from the code in your question -- then wait for the less.pageLoadFinished promise to resolve, as follows:
less.pageLoadFinished.then(function () {
'use strict';
let box1 = document.querySelector('#box1');
// ... etc
});
See updated fiddle

About image rotation once element with specific id is clicked

Logo and elements from ul once clicked rotates image. By default image is already rotated by certain degrees, then on each click image rotates to necessary value.
So far I was using the following:
$("#objRotates").css('opacity','.2');
var value = 0;
var prev_value = 0;
$( "li" ).click(function() {
var text=$(this).text();
if(text==="text1"){value=0;}
if(text==="text2"){value=33;}
if(text==="text3"){value=66;}
if(prev_value != value){
$("#objRotates").animate({opacity:'1'});
$("#objRotates").rotate({
animateTo:value,
easing: $.easing.easeInOutExpo,
center: ["25px", "150px"],
callback: function(){$("#objRotates").animate({opacity:'0.2'});}
});
}
prev_value = value;
});
Above code is the one that was used before, where images start position was 0 and its animation was triggered from link text.
Using jqueryRotate.js examples(here)
How do I change the code, so that images start position is certain degrees and animation starts if element with specific ID is clicked?
Give at least clue..Cause for now, looking at my old code, I am lost. Thanks in advance.
SIMPLIFIED FIDDLE
Ok, so I've created a couple of samples for you to check out. The first one is very basic and I've simplified the code a little to make it easier to understand. This one just uses completely static values and a static elementId for the event, which I'm pretty sure answers your question based on your response to my comment yesterday. http://jsfiddle.net/x9ja7/594/
$("#elementId").click(function () {
var startingAngle = 45;
var endingAngle = 90;
var elementToRotate = "img";
$(elementToRotate).rotate({
angle: startingAngle,
animateTo: endingAngle
});
});
But I wanted to give another example as well that would be dynamic and repeatable for multiple elements. With the code above, you would have to copy/paste the same code over and over again if you want to perform this animation by clicking different elements. Here's an alternative. In this example, you set all of your parameters in the data attributes in the clickable element, then the function is completely repeatable, you only have to write it once. Less code = everyone happy! Here's the example: http://jsfiddle.net/x9ja7/595/
//#region Default starting angles
$("#image1").rotate({ angle: 90 });
$("#image2").rotate({ angle: 20 });
//#endregion
$(".rotateAction").click(function () {
//#region Optional parameter - used in the optional callback function
var $self = $(this);
//#endregion
var startingAngle = Number($(this).attr("data-startingangle"));
var endingAngle = Number($(this).attr("data-endingangle"));
var elementToRotate = $(this).attr("data-elementtorotate");
//#region If the current angle is the ending angle, reverse the animation - this can be removed if you want, I thought it may be cool to show some of the things you can do with this.
var currentAngle = $(elementToRotate).getRotateAngle();
if ( currentAngle[0] === endingAngle) {
startingAngle = Number($(this).attr("data-endingangle"));
endingAngle = Number($(this).attr("data-startingangle"));
}
//#endregion
$(elementToRotate).rotate({
angle: startingAngle,
animateTo: endingAngle
//#region This is optional - uncommenting this code would make the animation single-use only
//, callback: function () { $self.off().removeClass("clickable"); }
//#endregion
});
});
Hope this helps. If you need any other assistance, please let me know.

Custom progress bar for <audio> and <progress> HTML5 elements

I am mind boggled at working out how to create a custom seekbar for an audio player using the tag and simple Javascript.
Current Code:
<script>
function play() {
document.getElementById('player').play();
}
function pause() {
document.getElementById('player').pause();
}
</script>
<audio src="sample.mp3" id="player"></audio>
<button onClick="javascript:play()" >Play</button>
<button onClick="javascript:pause()" >Pause</button>
<progress id="seekbar"></progress>
Would it be possible to link the progress bar so that when i play a song the progress is shown?
Yes, it is possible using the timeupdate event of the audio tag. You receive this event every time the position of the playback is updated. Then, you can update your progress bar using the currentTime and duration properties of the audio element.
You can see a working example in this fiddle
If you want smooth progress bar,try somethink like that
HTML:
<div class="hp_slide">
<div class="hp_range"></div>
</div>
CSS:
.hp_slide{
width:100%;
background:white;
height:25px;
}
.hp_range{
width:0;
background:black;
height:25px;
}
JS:
var player = document.getElementById('player');
player.addEventListener("timeupdate", function() {
var currentTime = player.currentTime;
var duration = player.duration;
$('.hp_range').stop(true,true).animate({'width':(currentTime +.25)/duration*100+'%'},250,'linear');
});
Pretty rough,but works
Here's a simple vanilla example:
const url = "https://upload.wikimedia.org/wikipedia/en/a/a9/Webern_-_Sehr_langsam.ogg";
const audio = new Audio(url);
const playBtn = document.querySelector("button");
const progressEl = document.querySelector('input[type="range"]');
let mouseDownOnSlider = false;
audio.addEventListener("loadeddata", () => {
progressEl.value = 0;
});
audio.addEventListener("timeupdate", () => {
if (!mouseDownOnSlider) {
progressEl.value = audio.currentTime / audio.duration * 100;
}
});
audio.addEventListener("ended", () => {
playBtn.textContent = "▶️";
});
playBtn.addEventListener("click", () => {
audio.paused ? audio.play() : audio.pause();
playBtn.textContent = audio.paused ? "▶️" : "⏸️";
});
progressEl.addEventListener("change", () => {
const pct = progressEl.value / 100;
audio.currentTime = (audio.duration || 0) * pct;
});
progressEl.addEventListener("mousedown", () => {
mouseDownOnSlider = true;
});
progressEl.addEventListener("mouseup", () => {
mouseDownOnSlider = false;
});
button {
font-size: 1.5em;
}
<button>▶️</button>
<input type="range" value="0" min="0" max="100" step="1">
The approach is to use an input[type="range"] slider to reflect the progress and allow the user to seek through the track. When the range changes, set the audio.currentTime attribute, using the slider as a percent (you could also adjust the max attribute of the slider to match the audio.duration).
In the other direction, I update the slider's progress on timeupdate event firing.
One corner case is that if the user scrolls around with their mouse down on the slider, the timeupdate event will keep firing, causing the progress to hop around between wherever the user's cursor is hovering and the current audio progress. I use a boolean and the mousedown/mouseup events on the slider to prevent this from happening.
See also JavaScript - HTML5 Audio / custom player's seekbar and current time for an extension of this code that displays the time.
First of all, don't use the progress element, it's a shitty element (for now) and styling it is a huge pain in... well it's boring (look at a little project I made, look at it (and it's juste webkit/moz)).
Anyway, you should read the doc on MDN, it's very easy and with a lot of examples. What you are looking for is the currentTime attribute, here a little snippet :
var audio = document.querySelector('#player')
audio.currentTime = 60 // will go to the 60th second
So what you need is to use the cross-multiplication (div is the element you use as a progress bar) :
Where I clicked on div | THE TIME I WANT TO KNOW
————————————————————————————————————————
Total length of div | The total time of my video/audio (audio.seekable.end())

Categories

Resources