I am trying to run this function set_downloads($file[0]); when the download button is clicked, i can't just add it in the code, as it will run. I can put it on a different page and do some sort of onclick event to load it, but i don't know how to do this.
<script type="text/javascript">
var x = 0;
var r = 0;
function countdown() {
if (x > 1) {
x--;
document.getElementById("button").innerHTML = x;
r = setTimeout("countdown()",0);
}
else {
clearTimeout(r);
document.getElementById("button").innerHTML = "Click to download (<?php echo $filesize;?>) ";
document.getElementById("button").disabled = "";
document.getElementById("button").onclick = function() {
document.getElementById("button").disabled = "disabled";
document.getElementById("button").innerHTML = "Your download is starting..";
};
}
}
setTimeout("countdown()",1000);
</script>
</head>
<body>
<label>
<font size="5"></font>
</label>
<a href="http://IP/uploads/<?php echo $fullfile; ?>" >
<button class="btn large orange" id="button" disabled="disabled">Click to download (<?php echo $filesize;?>) </button>
</a>
$(document).ready(function(){
var x = 0;
var r = 0;
function countdown() {
if (x > 1) {
x--;
document.getElementById("button").innerHTML = x;
r = setTimeout("countdown()",0);
}
else {
clearTimeout(r);
document.getElementById("button").innerHTML = "Click to download (<?php echo $filesize;?>) ";
document.getElementById("button").disabled = "";
document.getElementById("button").onclick = function() {
document.getElementById("button").disabled = "disabled";
document.getElementById("button").innerHTML = "Your download is starting..";
};
}
}
setTimeout("countdown()",1000);
$('.btn').click(function(){
set_downloads($file[0]);
});
});
This event handler is what you want to use to handle events. It uses a callback, which calls that function argument after the button is clicked.
The other thing is, I'm not sure about your $file[0] variable, or where your set_downloads function is defined. where do you set these?
Correct me if I am wrong but could you not just use a $(document).ready(handler) to ensure the DOM is loaded if needed then just use a onclick as you suggested:
.click( [eventData], handler(eventObject) )
eventDataA map of data that will be passed to the event handler.
handler(eventObject)A function to execute each time the event is triggered.
EDIT:
$('#button').click(function(){
set_downloads($file[0]);
});
Not sure if you would really need this inside a ready() but if so, you would just enclose the function for click() inside here:
$(document).ready( {
// Function for button goes here
});
EDIT#2
$(document).ready({
$('.btn').click(
{
$.ajax({ url: 'script.php?argument=value&foo=bar' });
)};
));
You could place your php script inside a seperate file and call it using ajax and the url: then set any arguments if needed. I wouldnt copy and paste what I put considering I am mobile and its difficult to see brackets :/
You could also take a look here, A slightly different example still using Ajax and Jquery but may work slightly nicer for your desired application:
Use Ajax to call PHP function for HTML button Onclick
Related
I have a page in php, and I'm trying to add an ?id=variable_value extension to it's url when I click on a div, but when I click it gives me an undefined url error with the extension
Here is the script:
<script language="javascript" type="text/javascript">
var Pokemon_ID = 1;
function changeUrl() {
location.href=this.href+'?id='+Pokemon_ID;return false;
}
document.getElementById( 'right-btn' ).onclick = function() {
changeUrl();
};
</script>
And the div :
<div id="right-btn" href="pokedex.php" onclick="changeUrl()">
Don't use two separate ways of attaching handlers when you only need one. Inline event handlers are essentially eval inside HTML markup - they're bad practice and result in poorly factored, hard-to-manage code. Seriously consider attaching your events with JavaScript, instead.
The problem is that when assigning the handler via onclick, the this in changeUrl is undefined, because the calling context is global. Feel free to avoid using this when it can cause confusion.
Just use addEventListener alone. Also, you'll have to use getAttribute('href') instead of .href because divs are not supposed to have href properties.
const Pokemon_ID = '5';
document.getElementById('right-btn').addEventListener('click', function(e) {
// location.href = e.target.getAttribute('href') + '?id=' + Pokemon_ID;
console.log('changing URL to ' + e.target.getAttribute('href') + '?id=' + Pokemon_ID);
});
<div id="right-btn" href="pokedex.php">text</div>
Try this instead:
location.href += '?id=' + Pokemon_ID;
Because you call changeUrl() within the onclick method you loose the context of this. This in changeUrl is not your div. Maybe you have to pass this into the method with changeUrl(this) or you just pass the href with changeUrl(this.href).
Than use:
function changeUrl(target){
location.href=target.href+'?id='+Pokemon_ID;
}
As mentioned by CertainPerformance above, you are not passing the right arguments to you function to work correctly; Using you code as a reference, you can either pass the original event to you changeUrl() function, then use the e.target to get to your 'right-btn' element.
Javascript:
var Pokemon_ID = 1;
function changeUrl(e) {
var href = e.target.getAttribute('href');
console.log(href +'?id=' + Pokemon_ID);
return false;
}
document.getElementById( 'right-btn' ).onclick = function(e) {
changeUrl(e);
};
HTML:
<div id="right-btn" href="pokedex.php">Click Me 4</div>
However, if you realy want to use this in your function to refer to the 'right-btn' element, then you can change the code to;
Javascript:
var Pokemon_ID = 1;
function changeUrl() {
var href = this.getAttribute('href');
console.log(href +'?id=' + Pokemon_ID);
return false;
}
document.getElementById( 'right-btn' ).onclick = function(e) {
changeUrl.call(e.target);
};
The changes being the call in the event handler:
changeUrl.call(e.target);, which calls you function in the 'context' of the e.target, making the this in your changeUrl() function to the element. Then you can use the this as in var href = this.getAttribute('href');
Just don't know why this piece of code is not working: (onClick not working, click() is working (using console))
function click(ID)
{
if(cost[ID] <= currency[costID[ID]])
{
currency[costID[ID]] -= cost[ID];
currency[ID] += buyamout[ID];
document.getElementById(x[costID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[costID[ID]])*100)/100)+not+"</center>";
document.getElementById(x[gainID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[gainID[ID]])*100)/100)+not+"</center>";
}
}
...'<button onClick="click('+i+');">'+button+x[i]+'</button>'
this gives output <button onClick="click(0);">Make DNA</button>
and after clicking button nothing happens.
There could be a namespace conflict with your click. Use another name like button_click below
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="button_click('+i+');" >'+(button+x[i])+'</button>');
function button_click(ID) { // notice the function name change
alert(ID);
}
Code below not working:
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="click('+i+');" >'+(button+x[i])+'</button>');
function click(ID) { // the function name click may have been used already
alert(ID);
}
indeed onclick="click('+i+');" executes the javaScript code between the double brackets: click('+i+');: it calls the javaScript click() function, but this does not work if you declare function click() and someone else did that elsewhere in javaScript code.
if onClick is not working you can also use addEventListener will do the same job.
for e.g.
element.addEventListener('click', function() { /* do stuff here*/ }, false);
To answer your question you must do the following.
Change:
onClick="click(0)"
To:
onclick="click(0)"
That will most probably fix your problem.
I noticed my users sometimes click the buttons twice, maybe no one told them one click is enough.
What's the best way to prevent the double-click?
I basically hide the button and show a "loading" gif, but that apparently is not enough...
Usually disabling/hiding/replacing the button should work. If they are real fast, try setting a variable to false when your script starts, return if it's true, set it to true after the first click.
var alReadyClicked = false;
function click(){
if (alreadyClicked)
return false;
alreadyClicked = true;
}
Don't forget to set it to false when the user can click again.
If they are clicking fast enough to fire the double click event, return false.
ondblclick="return false"
EDIT: This will not cancel the single click event so problem would still exist.
I just found out the jQuery funcion .one(), that may be useful great for this kind of purpose! great!
The equivalence to JQuery .one() may be the once option on AddEventListner like:
function doSubmit () { /* your code */ }
btn = document.getElementById ('foo');
btn.addEventListener ('click', doSubmit, {once: true});
Reference: javascript - JS equivalent for jQuery one() - Stack Overflow
Another example using a flag
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test dbl click</title>
</head>
<body>
<button id="btn1">Click Away</button>
<div id="out"></div>
<script type="text/javascript">
function addMessage( msg ){
document.getElementById("out").innerHTML += (new Date().toTimeString()) + " : " + msg + "<br/><br/>";
}
function singleClick(){
addMessage( "single");
}
function addDoubleClickProtection( element, fncToCall ){
var isClicked = false;
var timer = null;
element.onclick = function(){
if(!isClicked){
isClicked = true;
timer = window.setTimeout( function(){ isClicked = false; }, 200);
return fncToCall();
}
}
}
addDoubleClickProtection( document.getElementById("btn1"), singleClick );
</script>
</body>
</html>
Simple method by counting the submit button click and with minimum decoration will:
<script>
var click_count = 0;
function submit_once () {
document.forms.A.elements.cmd.forEach(
function(e,i,l){e.style.color="#888";});
return (click_count++ > 1);
}
function reset_count () {
document.forms.A.elements.cmd.forEach(
function(e,i,l){e.style.color="unset";});
click_count = 0;
}
</script>
<form name="A">
<button type="submit" name="cmd" value="doAdd"
onclick="return submit_once();">Do add</button>
<button type="submit" name="cmd" value="doDel"
onclick="return submit_once();">Do delete</button>
</form>
You can create a util function once which will take CB function. And all logic handles seamlessly. You don't have to create a global variable to count or update.
function once(cb) {
let once = false;
return (...args) => {
!once && cb(...args);
once = true;
};
}
// How to use it.
// Create/bind function
const log = once((data) => {
console.log(data);
});
// Use it
Promise.resolve("hellowold").then(log).then(log);
Above line print only once.
I am a beginner in javascript, can you tell me what's wrong with the below code?
I want this to invoke buttonPressed() when a button gets pressed. From buttonPressed() it should call changeColor1(), changeColor1() should change the text color of a paragraph, and start a timer to invoke changeColor2(). Similarly changeColor2() should also change the color and call changeColor1() once the timer expires.
<html>
<head>
<script type="text/javascript">
function changeColor2()
{
alert("2");
var v = document.getElementById("onet");
v.style.color = rgb(0,255,255); // this statement is not working
var t=setTimeout(changeColor1,3000);
}
function changeColor1()
{
alert("1");
var v = document.getElementById("onet");
v.style.color = rgb(255,255,0); // this statement is not working
var t=setTimeout(changeColor2,3000);
}
function buttonPressed()
{
alert("Hello");
changeColor1();
}
</script>
</head>
<body>
<p id="onet"> Hello how are you? </p>
<form>
<input type="button" value="Display alert box!" onClick="buttonPressed()" />
</form>
</body>
</html>
Do not invoke the function, pass the reference only:
var t=setTimeout(changeColor2,3000);
I think you want style.color not .color.
By the way... please tell us what the code is supposed to actually do and what is wrong initially.
You need to quote style property values-
v.style.color = 'rgb(255,255,0)';
1) I don't like the fact that you have two timeouts set. Just call one function and use a flag to toggle between the two options.
2) The parameter to setTimeout that you want to use is a function pointer (changeColor) not the result of a function call (changeColor())
var flag = false;
var t;
function changeColor()
{
var v = document.getElementById("onet");
if(flag){
v.color = rgb(255,255,0);
} else {
v.color = rgb(0,255,255);
}
flag = !flag;
}
function buttonPressed()
{
alert("Hello");
t=setInterval(changeColor,3000);
}
Not really knowing what it is you're trying to do, I can tell you that your button's onClick handler references a method name that isn't in your code. Judging by the names of your methods, I think you meant to put "buttonClicked" in there.
Nevermind, looks like you changed it while I was typing.
Instead of v.color = rgb(0,255,255); use v.style.color = "#0ff".
I want to add more functionality to an already rendered button code.
The only way to do it is Javascript since it's rendered before from the server and I only have access to the JSP.
Here is what I have now, but it's not working, it just displays the same message twice. And if I click the button, the alert "hello" is not shown.
<script type="text/javascript">
function addEventBefore(element, type, fn) {
var old = element['on' + type] || function() {};
element['on' + type] = function () { fn(); old(); };
}
function sayHello(){
alert('hello');
}
var arr = document.getElementsByTagName("button");
for (i = 0; i < arr.length; i++) {
if (arr[i].getAttribute("name") == "Complete"){
var theclick = arr[i].getAttribute("onClick");
alert(theclick);
addEventBefore(arr[i], 'Click', sayHello);
var theclick2 = arr[i].getAttribute("onClick");
alert(theclick2);
}
}
</script>
This is the rendered source code of the page:
<td valign='top' align='right' >
<button name="Complete" title="The complete Button"
onClick="document.forms.TaskInfoPage.action='http://prodserver:8080/Approval.jsp?windowId=dd4c0&eventTarget=stepApproval&eventName=Complete'
document.forms.InfoPage.submit();return false;">Complete</button>
</td>
So, I want to place the sayHello() before it does the action on the onClick.
It's onclick rather than onClick, so you need this:
addEventBefore(arr[i], 'click', sayHello);
// ^ lower case here
The attribute itself still isn't going to display anything different, but the event themselves will work, you can test it here. Also, to maintain this for your event handlers, I recommend you at least .call() the functions, like this:
function addEventBefore(element, type, fn) {
var old = element['on' + type] || function() {};
element['on' + type] = function () { fn.call(this); old.call(this); };
}