i have this function in my init.js
function bodyresize() {
var factor = ($window.width() * $window.height()) / (1440 * 900);
$body.css('font-size', Math.min(Math.max(Math.floor(factor * settings.sizeFactor), settings.sizeMin), settings.sizeMax) + 'pt');
$main.height(panels[activePanelId].outerHeight());
$body._reposition2();
};
$body._reposition2 = function() {
if (skel.vars.isTouch && (window.orientation == 0 || window.orientation == 180))
$wrapper.css('padding-top', Math.max((($window.height() - (panels[activePanelId].outerHeight() + $footer.outerHeight())) / 2) - $nav.height(), 30) + 'px');
else
$wrapper.css('padding-top', ((($window.height() - panels[firstPanelId].height()) / 2) - $nav.height()) + 'px');
};
now i need from my game1 scrip that when i press a button the code above runs
in my index.html i have this:
<head>
<script src="js/init.js" type="text/javascript"></script>
</head>
and the button i have this
<button id="button" onclick="bodyresize()">Click Me test</button>
i think something is wrong with the button because he cant find bodyresize but i cant find why
This is going against your original approach a little bit, but I would handle the entire thing in Javascript. It could look something like this:
document.getElementById('button').onclick = function(e) {
// your code
}
Here's a working example.
Edit:
Here's another example of a button working of onclick defined in the element itself. It looks similar to what you originally had.
Both of these approaches are technically correct, but if you define the onclick function inside init.js, you can't really reuse the file in another page, as the onclick function would throw an error when it couldn't find another component of the same name (button). A solution around this is define a new file.
Hope this helps you!
Related
How I would go about making a website that randomly redirects between multiple (in this case 2) websites?
Obviously what is below doesn't work due to what I hope is the meta tag; I would like to know if the javascript code is the correct way to do this
and how it would work.
<head>
<meta http-equiv="refresh" content="1;url=http://example1.com">
<script type="text/javascript">
if Math.random() =< 0.5;
window.location.href = "http://example1.com/"
else;
window.location.href = "http://example2.com"
</script>
<title>Page Redirection</title>
</head>
your javascript syntax inside script tag is not correct either
<script type="text/javascript">
if ( Math.random() <= 0.5 ) //proper parenthesis surrounding the condition and also < will come before =
window.location.href = "http://example1.com/";
else //semicolon removed from here
window.location.href = "http://example2.com";
</script>
You did it right (almost), Wrap the condition in () and remove ;, it will break the if.
if (Math.random() =< 0.5)
window.location.href = "http://example1.com/";
else
window.location.href = "http://example2.com";
Keep in mind one little fact.
if(false)
alert(1);
Won't alert anyting as the if condition is always false. But if you see
if(false); // If will break here.
alert(1);
Will always alert as if breaks and then the execution proceeds without if.
You could make the function a little bit more generic:
var sites = [
'http://www.dilbert.com',
'http://stackoverflow.com',
'http://Starwars.com'
];
var target = Math.floor(Math.random() sites.length);
window.location = sites[target];
So when your site collection grows you don't need to alter the code. You could even pack it into a function:
function goRandomSite(sites) {
var target = Math.floor(Math.random() sites.length);
window.location = sites[target];
}
Hope that helps
Hi I'm trying to work on a problem solving webpage that I need for school but so far I'm stuck with the if statement which it will use to calculate.
What I have so far.
<script>
var randomNumberA = Math.round((Math.random() * 50) +1)
var randomNumberB = Math.round((Math.random() * 50) +1)
document.write('He runs at ' + randomNumberA + 'm/s which took him ' + randomNumberB + 's. How far did he run?');
var distance = randomNumberA * randomNumberB
function Submit()
{
var answer = document.getElementById('answer')
if(distance == true){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
</script>
<body>
<input type='text' id='inputAnswer'/>
<input type='button' onClick='Submit()' value='Submit'/>
</body>
It's not really working and if I put only one "=" then it'll alert as true as long as there's a value in the text box. I plan to make a variable for the textbox value and a variable for the formula and just put If(var1=var2)... so on, but it doesn't work. I'd like to know if it's possible, and if it is how?
If it's not possible can I try to place var1 = formula = textbox id. I'm trying to make it so one variable contains the values that need to be equal so when I declare it in the if statement, I'll just test if it's true or false.
All help is appreciated thanks!
You should compare the calculated distance to the given answer. Now you compare distance to true, which doesn't make sense.
Change it to
if(distance == parseFloat(answer.value)){
You need .value, because answer points to the element. You don't want to compare distance to the element, but to the numeric representation of the element's value.
Also note that you have the id wrong. In html it is inputanswer, while in your script you called it answer.
The version with a single = works, because you assign a value to distance. An assignment can also be used as an expession, which returns the value that was assigned. So if you write if (distance = true), you assign true to the variable distance, and also return true from the expression, resulting in the code inside the if always being executed.
I've made the necessary fixes in the code below, which you can just run from here. As you can see, you were almost there. I just needed to make those two small fixes. :)
var randomNumberA = Math.round((Math.random() * 50) +1)
var randomNumberB = Math.round((Math.random() * 50) +1)
document.write('He runs at ' + randomNumberA + 'm/s which took him ' + randomNumberB + 's. How far did he run?');
var distance = randomNumberA * randomNumberB
function Submit()
{
var answer = document.getElementById('inputAnswer')
if(distance == parseFloat(answer.value)){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
<body>
<input type='text' id='inputAnswer'/>
<input type='button' onClick='Submit()' value='Submit'/>
</body>
Not completely sure that I understand your question. But, here's some info that will hopefully help:
if(distance == true){
This will render true if there's a value, unless the value is set to false. It's like saying:
if (distance)
If you want to test to see if the value matches the formula, you would just do something like this:
function Submit()
{
var answer = document.getElementById('inputAnswer').value // not 'answer'
if(distance === answer){
alert("Congrats! You got it right!");
} else{
alert("Try again!");
location.reload();
}
}
Hope that helps
you could also get the value via JQuery if your'e using that. It would be the following:
var answer = $('#inputAnswer').val();
Cheers!
I made a div and a button. Made a function on button's click that set div's margin (i.e move it). But how can I make it move on every click. Whenever I hit the button it do moves, (without refreshing the page) when I press that button again it don't work? How to make it move on every click of button! Here's my code:-
<!DOCTYPE html>
<html>
<head>
<title>JavaScript</title>
<style>
body
{
font-family:ebrima;
}
</style>
</head>
<body onload="" id="demo">
<div name="player" style="float:right; height:32px; width:32px; background:green;" id="myDiv"></div>
<form name="myForm" method="post">
<button value="MOVE" type="button" name="moveButton" onClick="move()">MOVE</button>
</form>
<script>
function move()
{
document.getElementById("myDiv").style.margin="0px 10px 0px 0px";
}
</script>
</body>
</html>
Use a variable to set the new margin each time. After using it, change the variable's value so that next time, it will move somewhere else.
var x = 10;
function move() {
document.getElementById("myDiv").style.margin="0px "+x+"px 0px 0px";
x = x+10;
}
First, don't use inline js (like onclick). Read some of these results: *Why is inline js bad?*
Instead, attach your event listener with javascript:
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
Your code would be more readable/efficient and easier to debug like this:
//cache element reference in advance
var document.getElementById("myDiv")
function move() {
//just target the property you want to change.
myDiv.style.marginLeft = x+'px';
x = x+10;
}
Here's a little demo (click) I put together you may enjoy.
var myDiv = document.getElementById('my-div');
var myBtn = document.getElementById('my-btn');
myBtn.addEventListener('click', move);
function move(e) {
var v = r()+'px '+r()+'px '+r()+'px '+r()+'px';
myDiv.style.margin = v;
}
function r() {
return getRandomInt(0, 20);
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1) + min);
}
And here's a more fun one using mousemove rather than click. Demo here.
I would advise using jQuery, which makes a lot of javascript quite simple.
Here's a sample jQuery animation for you:
<script>
function move() {
$("#myDiv").animate({left:'+=250px'});
}
</script>
This will shift the button over by 250px every time you trigger the function.
Note that you'll need to add jQuery to your project (which is trivial). The jQuery website has some well organized tutorials that should help you find your way around JavaScript and jQuery - happy coding!
Like this:
function move() {
var elt = document.getElementById("myDiv"),
currentMargin = parseInt(elt.style.marginRight, 10);
elt.style.marginRight = currentMargin + 10 + 'px';
}
I am having an issue implementing this calculator on my website which i created. I think i have used the wrong javascript to create the simple calculation which is the following math calculation: ((list price - rrp) / list price) * 100
PLEASE NOTE, i am aware of the values not being numbers, please replace them with any numbers. it still doesnt work.
This is to get the percentage value of the discount against the list and the RRP.
Please review the code before HTML:
<script type="text/javascript">
discountFinal(#OriginalPrice, #ListPrice);
</script>
<div id="discountCode">
<span id="spanish"></span>
<span id="spanishtwo">%</span>
</div>
Javascript:
var discountFinal = function (firstly, secondly) {
var totalfirst = secondly - firstly;
var totalsecond = totalfirst / secondly;
var totalthird = totalsecond * 100;
if (document.getElementById("discountCode").innerHTML === null) {
document.getElementById("spanishtwo").innerHTML.replace("%", "")
} else {
document.getElementById("spanish").innerHTML = Math.floor(totalthird / 5) * 5
}
};
I dont think i am calling the function within the html properly. Can someone assist with this please.
http://jsfiddle.net/xwzhY/
I'm not sure the error you're getting, but it seems as if you're calling the discountFinal function before it's defined. When you move the call, it starts to work:
http://jsfiddle.net/bmonty/xwzhY/4/
Edit after comment from OP.
You just need to make sure your discountFinal function is defined at the top of your page, before any place it gets called.
This will work:
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
But this will throw an error:
<script type="text/javascript">
var result = discountFinal(1, 2);
</script>
<script type="text/javascript">
var discountFinal = function(a, b){};
</script>
To get some clarification, View Source on the HTML page from your browser to see what the resulting page looks like. That should point out where the order of operations is getting messed up.
It works fine if you call your function after it exists: http://jsfiddle.net/xwzhY/2/
Just make sure that the function is declared earlier in the code than you use it. Or declare it using a function statement rather than a function expression assigned to a variable:
function discountFinal(firstly, secondly){
...
Trying put "" around your perl variable, you need to pass the value
I have been building my own carasol over the past few days.
My Jquery is based on tutorials on the web and also from help and advice from SO.
I am not a Jquery guru just an enthusiast and think my code is a little sloppy, hence the post.
here is a link to the working code: http://jsfiddle.net/JHqBA/2/ (updated link)
basically what happens is:
if someone hits the page with a # values in the url it will show the appropriate slide and example would be www.hello.com#two, this would slide to slide two
if someone clicks the numbers it will show the appropriate slide
next and prev also slide through the slides.
The question is, is there anything i could have wrote better as i know there is alot of duplicate code.
I understand its a big ask but it would help me learn a little more (i think my code is a little old school)
if anyone has any questions please feel free to ask and ill answer what it does or is supposed to do.
Sluap
--- Edit ----
I have made only one aniamtion function now which has got rid of alot of duplicate code.
I have yet to look into on function but will do soon.
I would like to know more about the create a new function, outside of the jQuery ready block as i cant get this working or quite understand how i can get it to work sorry
any more tips would be great ill carry on working on this project till i am happy with it.
also is there a better way to write:
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
Jquery full:
$(document).ready(function () {
//////////////////////////// INITAL SET UP /////////////////////////////////////////////
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
//set the initial not active state
$('#prev').attr("class", "not_active");
//////////////////////////// SLIDER /////////////////////////////////////////////
//Paging + Slider Function
rotate = function () {
var triggerID = $slideNumber - 1; //Get number of times to slide
var image_reelPosition = triggerID * divWidth; //Determines the distance the image reel needs to slide
//sets the active on the next and prev
if ($slideNumber == 1) {
$('#prev').attr("class", "not_active")
$('#next').attr("class", "active")
}
else if ($slideNumber == divSum) {
$('#next').attr("class", "not_active");
$('#prev').attr("class", "active");
}
else {
$('#prev').attr("class", "active")
$('#next').attr("class", "active")
};
//Slider Animation
$(".image_reel").animate({
left: -image_reelPosition
}, 500);
};
//////////////////////////// SLIDER CALLS /////////////////////////////////////////////
//click on numbers
$(".paging a").click(function () {
$active = $(this); //Activate the clicked paging
$slideNumber = $active.attr("rel");
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
});
//click on next button
$('#next').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) + 1);
$slideNumber = slideNumber;
if ($slideNumber <= divSum) { //do not animate if on last slide
rotate(); //Trigger rotation immediately
};
return false; //Prevent browser jump to link anchor
}
});
//click on prev button
$('#prev').click(function () {
if (!$(".image_reel").is(':animated')) { //prevent clicking if animating
var left_indent = parseInt($('.image_reel').css('left')) - divWidth;
var slideNumberOn = (left_indent / divWidth);
var slideNumber = ((slideNumberOn * -1) - 1);
$slideNumber = slideNumber;
if ($slideNumber >= 1) { //do not animate if on first slide
rotate(); //Trigger rotation immediately
};
}
return false; //Prevent browser jump to link anchor
});
//URL eg:www.hello.com#one
var hash = window.location.hash;
var map = {
one: 1,
two: 2,
three: 3,
four: 4
};
var hashValue = map[hash.substring(1)];
//animate if hashValue is not null
if (hashValue != null) {
$slideNumber = hashValue;
rotate(); //Trigger rotation immediately
return false; //Prevent browser jump to link anchor
};
});
Question and answer has been moved over to https://codereview.stackexchange.com/questions/8634/jquery-carasol-build-finished-and-would-like-advice-on-best-practice-neateni/8635#8635
1) Separation of Concerns
Start by refactorring your code in to more granular functions.
You can read more about SoF at http://en.wikipedia.org/wiki/Separation_of_concerns
Update:
E.g. Instead of having your reel resizing code inline, put it in it's own function, like this:
function setImageReelWidth () {
//Get size of images, how many there are, then determin the size of the image reel.
var divWidth = $(".window").width();
var divSum = $(".slide").size();
var divReelWidth = divWidth * divSum;
//Adjust the image reel to its new size
$(".image_reel").css({ 'width': divReelWidth });
}
This achieves 2 things:
a. First, it groups a block of code that is logically cohesive, removing it from the main code which results in a much cleaner code habitat.
b. It effectively gives a label to the code block via the function name that is descriptive of what it does, and therefore makes understanding of the code much simpler.
Later, you can also encapsulate the whole thing in it's own "class" (function) and you can move it into it's own js file.
2) The jQuery "on" function
Use the "on" function to attach your click events, rather than the "click" function.
http://api.jquery.com/on/
This has the added advantage of also binding it to future elements matching your selector, even though they do not exist yet.
3) The ready function
// I like the more succinct:
$(handler)
// Instead of:
$(document).ready(handler)
But you might like the more obvious syntax.
Those are just a few things to start with.
-- Update 1 --
Ok, StackOverflow is not really suited to a refactoring work in progress, but we'll make do. I think you should keep your original code block in your question, so that future readers can see where it started and how it systematically improved.
I would like to know more about the create a new function, outside of
the jQuery ready block as i cant get this working or quite understand
how i can get it to work sorry
I am not familiar with jsfiddle.net, but it looks cool and helpful, but might also be a bit confusing if you don't know what is going on. I am not sure I do :), but I think that script editor window results in a .js file that is automatically referenced by the html file.
So here is an example of a function defined outside of the ready block, but referenced from within.
function testFunction () {
alert ('it works');
}
$(document).ready(function () {
testFunction();
// ... other code
});
This should pop up an alert box that says, "it works" when the page is loaded.
You can try it for yourself.
Then, once you got that working, you can refactor other logically cohesive blocks of code into their own functions. Later you can wrap them all up into their own javascript 'class'. But we'll get to that.