How do I create a Random Border Radius? - function

In the Javascript portion of The Complete Web Developer Course on Udemy, Rob (the teacher) makes a div randomly become either a circle or square based on a simple if-then statement. But how would I create a square with a completely random border radius?
function getRadius() {
var radius=Math.random();
radius = radius * 100;
}
function makeBox() {
var time=Math.random();
time=time*2000;
setTimeout(function() {
document.getElementById("box").style.borderRadius="50px";
document.getElementById("box").style.backgroundColor=getRandomColor();
document.getElementById("box").style.display="block";
createdTime=Date.now();
}, time);
}
The program works when I have just have an integer with px after like in the example, but I can't seem to figure out how to change the 50 to the function getRadius, if that makes sense. Nothing appears with

html:
<div id="box" onclick="change();">
<p>click me</p>
<div>
css:
#box{
height:100px;
width:100px;
background-color:red;
}
js:
function change(){
var num = Math.floor(Math.random() * 100);
box.style.borderRadius= num+'px';
};

Related

A hover-activated 3D Parallax effect on my website

I want to create a hover-activated 3D Parallax Effect for my homepage.
I want to achive something like that:
https://www.hellomonday.com/
It has a 3D effect but also it is responsive to my mouse movement. What should I search? How can I create this effect?
Parallax.js by Matt Wagerfield (#mwagerfield) and Claudio Guglieri (#claudioguglieri)
It is a robust little parallax engine, giving you a quick, simple api to get going with all your parallax needs. Forget scrolling though, parallax.js utilizes your devices orientation and will fall back to cursor positions if no motion detection is available… this really gives you that sexy responsive feel.
May be this could help you to acheive what you are seeking for :)
Alternatively if you want to use Primitive JS Then you have to track the movement of mouse and trigger some event accordingly.
<!DOCTYPE html>
<html>
<head>
<style>
div {
width: 200px;
height: 100px;
border: 1px solid black;
}
</style>
</head>
<body>
<div id="myDIV"></div>
<p>Mouse over the rectangle above, and get the coordinates of your mouse pointer.</p>
<p id="demo"></p>
<p id="demo1"></p>
<script>
document.getElementById("myDIV").addEventListener("mousemove", function(event) {
myFunction(event);
});
function myFunction(e) {
var x = e.clientX;
var y = e.clientY;
var coor = "Coordinates: (" + x + "," + y + ")";
document.getElementById("demo").innerHTML = coor;
if( x == "54")
alert("Cordinate triggered")
}
</script>
As soon as you hit x coordinate as 54, alert box will appear

Multiline text on HTML5 canvas

So I'm trying to create a Meme generator using the HTML5 canvas. I understand I can write on the canvas using the following:
ctx.filltext()
However, I can only write on the canvas once. Does anyone know how I could write on the canvas more than once or even twice as in multiple times. As with Meme generators they have one line of text at the top and one at the bottom of the image. If it's not possible could anyone let me know or point me in the direction of a tutorial/answer that could let me write on top of an image with text including changing the font and font size plus top/bottom, left/right.
Thanks to anyone who can help.
You can create a function that draws text given your desired styling arguments:
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
drawText('This is the top',canvas.width/2,20,24,'verdana');
drawText('This is the bottom',canvas.width/2,canvas.height-20,16,'Courier');
function drawText(text,centerX,centerY,fontsize,fontface){
ctx.save();
ctx.font=fontsize+'px '+fontface;
ctx.textAlign='center';
ctx.textBaseline='middle';
ctx.fillText(text,centerX,centerY);
ctx.restore();
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }
<canvas id="canvas" width=300 height=300></canvas>

Random Image Position in programming website?

I want to make it so I have "enemies" spawn in the background (not THE background, just images on top of it) of a particular webpage at random heights and scroll across the screen. Right now I have something like:
<script>
function numberRandomizer(){
var x = Math.floor((Math.random() * 500) + 300); //random number between 300 and 800
return x;
}
</script>
I've tried 2 methods to applying this random variable X to the images that loop by scrolling on screen:
1) Doing what I thought would work and editing each image to get a random value for top and left
<marquee behavior="scroll" direction="left" scrollamount="numberRandomizer()"><img src="/aboutme/enemy.png" width="120" height="80" top="numberRandomizer()" left="numberRandomizer()"/><p></marquee>
2) Even though as far as I know it would make all enemies have the same position, try out CSS styling to make the placement random just to see if it would work:
<style>
img {
top: numberRandomizer();
left: numberRandomizer();
}
</style>
Neither style works in setting a random value for the image location, am I getting a minor thing wrong or going about this completely the wrong way?
As a bonus question: Is it possible to set marquee to go a random direction per image?
You can make the same thing using plain javascript too
html:
<marquee behavior="scroll" direction="left" id="elem">Test</marquee>
<br/>
<button id="butR">Right</button>
<button id="butL">Left</button>
<div class="area">
<div id="enemy"></div>
</div>
Js:
document.getElementById('butR').addEventListener("click", function(){
document.getElementById('elem').setAttribute("direction", "right");
});
document.getElementById('butL').addEventListener("click", function(){
document.getElementById('elem').setAttribute("direction", "left");
});
function numberRandomizer(){
var x = Math.floor((Math.random() * 250) + 50); //random number between 50 and 300
return x;
}
document.getElementById('enemy').style.top = numberRandomizer() + 'px';
document.getElementById('enemy').style.left = numberRandomizer() + 'px';
I've added also a way to change marque direction. Take a look at this fiddle:
https://jsfiddle.net/oyv324z9/
As a couple people said, you can't mix JS and CSS. If you are using jQuery though, this is pretty simple. Basically, you want to use jQuery to add CSS styles to the img. Something like this.
//your trigger here and then..
$( "#your_img_id" ).css( "left", function(index) {
return index * numberRandomizer() ;
});
$( "#your_img_id" ).css( "right", function(index) {
return index * numberRandomizer() ;
});

HTML5 progress bar animation

I am using an HTML5 progress bar in my app. I would like to know if there is any way to control the animation speed of the progress bar. I want to show the progress after a certain interval, which I did using the setTimeout method of javascript so that it sets the value after the screen has been rendered. But the animation is too fast. Is there any way to control it?
Thanks.
I'm not sure I understand what you mean by "animation" but here is an example of using the progress bar while controlling the speed of progression: http://jsfiddle.net/526hM/
Html:
<progress max="200" value="1"></progress>
<div id="val"></div>
Script:
$(document).ready(function(){
var interval = 2, //How much to increase the progressbar per frame
updatesPerSecond = 1000/60, //Set the nr of updates per second (fps)
progress = $('progress'),
animator = function(){
progress.val(progress.val()+interval);
$('#val').text(progress.val());
if ( progress.val()+interval < progress.attr('max')){
setTimeout(animator, updatesPerSecond);
} else {
$('#val').text('Done');
progress.val(progress.attr('max'));
}
}
setTimeout(animator, updatesPerSecond);
});
Here is example.
JavaScript function:
window.onload = addTenPercent();
function addTenPercent() {
var bar = document.getElementById("progressBar");
setInterval(addTenPercent, 100);
bar.value += 5;
};
HTML:
<progress id="progressBar" max="100" value="0"></progress>
Mantas' answer above looks good and works (without having to use jQuery), but I wonder if we could also use the setTimeout function? Would setTimeout in a recursive function that exits after 100 iterations also work? Copying Mantas' code from above and changing it a little:
JavaScript:
function onWindowLoad(){ // to be called by onload event
var bar = document.getElementById("progressBar");
addOne();
}
function addOne() {
if (bar.value < 100) { // this is the max value of the bar and the # of iterations
setTimeout(addOne, 80); // this literal value controls the speed
bar.value += 1;
}else{
return;
}
}
HTML:
<progress id="progressBar" max="100" value="0"></progress>

highlight word in div using javascript

hi i have to implement find and replace functionality in my project. in this functionality there is one find and replace button on the top of contenteditable div. when user click on this button, popup window will open and ask for the search word when specify word and press find it will find word in that div only. and if match found it will highlight that word. so anybody tell me how can i highlight word in div. its urgent so please . thank you.
<div id="test" contenteditable="true">
this is test <font class='classname'> some text test</font>
</div>
i want to high light only test word not else
You will need to search through the div to find the word and then put that word into a span, and change the background color of the span.
Edit: I just noticed that you are not using CSS, so you will need to insert a font tag to change the color.
I just stole this from Sphix, the documentation tool:
/**
* highlight a given string on a jquery object by wrapping it in
* span elements with the given class name.
*/
jQuery.fn.highlightText = function(text, className) {
function highlight(node) {
if (node.nodeType == 3) {
var val = node.nodeValue;
var pos = val.toLowerCase().indexOf(text);
if (pos >= 0 && !jQuery.className.has(node.parentNode, className)) {
var span = document.createElement("span");
span.className = className;
span.appendChild(document.createTextNode(val.substr(pos, text.length)));
node.parentNode.insertBefore(span, node.parentNode.insertBefore(
document.createTextNode(val.substr(pos + text.length)),
node.nextSibling));
node.nodeValue = val.substr(0, pos);
}
}
else if (!jQuery(node).is("button, select, textarea")) {
jQuery.each(node.childNodes, function() {
highlight(this)
});
}
}
return this.each(function() {
highlight(this);
});
}
/**
* helper function to hide the search marks again
*/
hideSearchWords : function() {
$('.sidebar .this-page-menu li.highlight-link').fadeOut(300);
$('span.highlight').removeClass('highlight');
},
/**
* highlight the search words provided in the url in the text
*/
highlightSearchWords : function() {
var params = $.getQueryParameters();
var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
if (terms.length) {
var body = $('div.body');
window.setTimeout(function() {
$.each(terms, function() {
body.highlightText(this.toLowerCase(), 'highlight');
});
}, 10);
$('<li class="highlight-link"><a href="javascript:Documentation.' +
'hideSearchWords()">' + _('Hide Search Matches') + '</a></li>')
.appendTo($('.sidebar .this-page-menu'));
}
},
So, adding this to a js file in your site, any page with it that receives a highlight GET parameter will search and highlight the word in the page.
You can find a demo of the working code in:
http://sphinx.pocoo.org/intro.html?highlight=python
Note: This code needs jQuery, off course...
Its actually pretty easy using the prototype library:
<html>
<head>
<style type="text/css">
#content span {
background-color: yellow;
}
</style>
<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript">
Event.observe(window,'load',function(){
var htm = $('content').innerHTML;
$('content').innerHTML = htm.sub('my','<span>my</span>');
});
</script>
</head>
<body>
<div id="content">
This is the div containing my content.
</div>
</body>
</html>
This should get you started so you can implement the rest.
To highlight a word you have to select it somehow. One option is to surround the word with a span tag.
this is <span class="highlight">test</span> some text test
then specify CSS for the highlight class.