I have a function that executes on page load. The function executes every 30 seconds using setTimeout. I want to be able to enable and disable setTimeout onclick I have the following code below...
<input id="vw" value="" type="hidden">
<a href="#" onclick="document.getElementById('vw').value='0';>click here</a>
<script>
/* JAVASCRIPT BELOW */
function mPb(){
var vw = escape(document.getElementById('vw').value);
if(vw == ''){//DO NOT SWITCH VIEW IF EMPTY
var sTo = setTimeout("mPb()", 30000);
} else {
clearTimeout(sTo);
}
}//END VIEW MY FEED
//ON SERVICE LOAD DISPLAY SHITE INSTEAD OF ONLOAD
window.addEventListener ?
window.addEventListener("load",mPb,false) :
window.attachEvent && window.attachEvent("onload",mPb);
</script>
Your code works if you properly close your onclick attribute with a double quote:
click here
Also, here go two little suggestions to improve your code:
If you're checking for an empty string inside your function, why setting the input value to 0 when you click the link? It works, but it would be more clear if you set the value to ''.
When using setTimeout (and setInterval), do not pass a string containing a function call. It works too, but it's dangerous. Use this instead:
var sTo = setTimeout(mPb, 30000);
sTo needs to go outside of the mPb function, that way you can reference it from you onclick.
Related
I have a function that is triggered by "Calculate" button
I need this line to only run once per session (session could be 1 day or until browser is reloaded).
$('.popup-with-form').magnificPopup('open');
This opens a Magnific Popup. Once this function is executed (popup opens), if "calculate" button is pressed again, I don't want popup to open again.
JS / JQuery code:
function StateChanged() {
if (XmlHttp.readyState == 4 || XmlHttp.readyState == "complete") {
$('.popup-with-form').magnificPopup('open');
document.getElementById("CalcSum").innerHTML = XmlHttp.responseText;
document.getElementById("CalcSumPopup").innerHTML = XmlHttp.responseText;
}
}
PS I know many of these questions pop up, and I tried different ways of doing thing, but since I'm "code-challanged" and do not know JQuery or JS I can't figure it out. I know there is a .one "thing" in JQuery, but don't understand how to make it work.
If you want to execute this line only once per browser session you can use sessionStorage. When you set a variable on sessionStorage it keeps its value until the browser closes (e.g. until you close Google Chrome).
So you can do something like:
if (!sessionStorage.alreadyClicked) {
$('.popup-with-form').magnificPopup('open');
sessionStorage.alreadyClicked = 1;
}
Be careful with sessionStorage because it can only store string values.
If you want the line to be executed only once per page session (which means once every page refresh) then you can use any variable and set it to true to remember you already executed the line:
if (!window.alreadyClicked) {
$('.popup-with-form').magnificPopup('open');
alreadyClicked = true;
}
Try
Edit, v2
I read about .one but could not figure it out :( ... I actually need
it to run once ONLY when CALCULATE button is pressed. – Roofing
Calculator
html
<!-- removed `action="javascript:GetInfo();"
, accept-charset="UNKNOWN"
, enctype="application/x-www-form-urlencoded"
, method="post"`
from `form` attributes -->
<form id="formcalc" style="text-align: left;">
<!-- changed `input` `type` to `button` -->
<input name="calculate" type="button" value="Calculate" />
</form>
js
$("#formcalc > input[name='calculate']")
.one("click", function(e) {
e.stopPropagation();
GetInfo();
});
v1
$("a.popup-with-form").one("click", function(e) {
// do stuff, once
// i.e.g.,
// `XmlHttp.onreadystatechange = StateChanged;` at `ShowSum()`
$(e.target).remove(); // remove element when `click`ed once
});
jsfiddle http://jsfiddle.net/guest271314/7K3tn/
See http://api.jquery.com/one/
Please use below.
disableOn
null
If window width is less then number in this option - lightbox will not be opened and default behavior of element will be triggered. Set to 0 to disable behavior. Option works only when you initialize Magnific Popup from DOM element.
Can also accept Function as a parameter, which should return true if lightbox can be opened andfalse otherwise. For example:
disableOn: function() { if( $(condition) { return false; } return true; }
I have a simple function to show / hide a div element. I have a javascript function to do that. I debugged this with Opera. The function sets the hidden value properly on the div element. I can see the div element disappear. However, when the function returns the div element reappears. The javascript function is in its own file:main.js:
function showhide(name){
var elem = document.getElementById(name) ;
if( elem.hidden == false ) {
document.getElementById(name).hidden = true ;
} else {
document.getElementById(name).hidden = false ;
}
}
The Html is:
<div class=wrap><p>
<div class=sidebar>
<FORM><input type="submit" value="Toggle" onclick="showhide('specname');"/></FORM></div>
<div class=main>main Div
<div id="specname">collapsible text</div></div></p></div>.
I have set debugging breakpoints in the javascript function showhide to see that the value is being set properly. But on function return, the value is reset.
It is probably something simple I am missing but can't seem to see it? Any ideas? Thanks!
The answers solved my problem. I was missing the fact that the submit repainted the page and I lost my changes. I changed the type=submit to type=button. And I removed the form to just an input element with type button. That worked very nicely. Thanks everyone for your help!!! I really appreciate your answers!
The following wont do anything in some browsers:
document.getElementById(name).hidden = true
change it to
document.getElementById(name).style.display = 'block' // and 'none' for the matching line
does that make it do what you need?
As others have pointed at, it is also submitting the page - either use a different element or change the function to start :
function showHide(e, name) {
e.preventDefault();
//do the toggle here
return false;
}
The problem is you are using a submit control which will submit to the server and refresh the page. You want to stop the submit or change the control type. Both of the following should work. I recommend the 2nd one.
Try this
<FORM><input type="submit" value="Toggle" onclick="showhide('specname'); return false;"/>
or this
<input type="button" value="Toggle" onclick="showhide('specname');"/>
Probably because when you click the button the form submits and it refreshes the page ?
You should not be using a form just to have a button that does something. Instead, try using
<button onClick="showhide('specname');">Toggle</button> (and get rid of the form entirely)
Try this for your showhide().
function showhide(name){
var elem = document.getElementById(name);
(elem.style.visibility == 'hidden'?elem.style.visibility = 'visible':elem.style.visibility = 'hidden');
}
OR similarly:
function showhide(name){
var elem = document.getElementById(name);
(elem.style.display== 'none'?elem.style.display= 'inline':elem.style.display= 'none');
}
Maybe try them both and see which you need.
Cheers.
how can i alert the user if there are any changes inside the object field
i''m trying to detect the changes on this div inside the object
if it's normal the code would be this:
<div id="HeaderNewMessageIcon" class="BrosixContactNewMessage" style="display:none;">
</div>
but if there are changes it will look like this:
<div id="HeaderNewMessageIcon" class="BrosixContactNewMessage" style="display: block; ">
</div>
i want to alert the user if there are changes inside the object, either via alert or using an image.
is there any way for me to achieve this?
and another thing, i have no access to the code inside the object, i can only view it but not edit it.
I believe there must be some JavaScript code which changing your html you can call your method from there. Other way you can use setInterval.
You can use jQuery plugin Mutation Events plugin for jQuery . see thread
var a = document.getElementsByClassName('HeaderNewMessageIcon')[0];
var oldTitle = a.title;
setInterval(function(){
if(a.title !== oldTitle){
alert("Title change");
oldTitle = a.title;
}
},100);
jsfiddle
You have to detect the changes when throught user interaction such as click, mouseover, mousedown, etc... then you can attach a function to see if its attributes or anything inside it changes.
//detect inputs change
$('#HeaderNewMessageIcon').find(':input').change(function(){ alert(...)});
//detect attributes change
$('#HeaderNewMessageIcon').click(function(){
detectChange(this);
});
As for detectChange to work, you must save the attributes when page just loaded
var attrs = $('#HeaderNewMessageIcon').get(0).attributes;
function detectChange(obj){
//pseudo-code, you need to find a function on the web to commpare 2 objetcs
if (obj.attributes === attrs){
alert(...);
}
//the same comparison for the children elements $(obj).children()
}
I wish to show out other objects when the onclick function is clicked. When i click that button, it will hide one object and show two other objects. I have already set the style.visibility to visible. But the show two object does not works.
Update Sample:
<input type="submit" id="show" name="show" value="show" onclick="RemoveDoc(); document.getElementById('docname').style.visibility='hidden'; document.getElementById('browse').style.visibility='visible'; return false;" />
//browse input
<input type ="file" name="browse" id="browse">
Method 2:
//Using my RemoveDoc() function, I want the button of browse being show out.
function RemoveDoc(Doc)
{
xmlhttp1=new XMLHttpRequest();
xmlhttp1.open("GET","functions/remove.php?Doc="+Doc,true);
xmlhttp1.onreadystatechange=function()
{
if (xmlhttp1.readyState==4 && xmlhttp1.status==200)
{
//when i run debugging, it says that the style of null..
document.getElementById("browse").style.visibility='visible';
}
}
xmlhttp1.send();
return false;
}
</script>
I tried two methods which both also cant show the browse button.
It should call out my visible on browse object as it's visible.. kindly advise.
http://jsfiddle.net/y3Bad/
A few things: you should include the visibility code inside of your removeDoc function, and bind the handler from javascript, not in markup. Also, your variable xmlhttp1 is an implicit global. Your removeDoc function takes a parameter, Doc, but you never pass anything to it. Finally, removeDoc makes an ajax call, which is asynchronous, so your line of code to show the browse button will not execute immediately, and may never execute at all if your ajax calls fails.
HTML:
<input type="button" id="show" name="show" value="show" />
JS:
document.getElementById('show').onclick = function () {
// use display instead of visibility if you don't want the hidden element to take up space
// setting visibility to empty string will show the element
document.getElementById('browse').style.visibility = '';
};
I use these two functions:
function hide(objId) {
document.getElementById(objId).style.display="none";
}
function show(objId) {
document.getElementById(objId).style.display="";
}
Maybe you can try to use jQuery, something like this:
http://jsfiddle.net/7fJuu/
I'd like to change the value of the onclick attribute on an anchor. I want to set it to a new string that contains JavaScript. (That string is provided to the client-side JavaScript code by the server, and it can contains whatever you can put in the onclick attribute in HTML.) Here are a few things I tried:
Using jQuery attr("onclick", js) doesn't work with both Firefox and IE6/7.
Using setAttribute("onclick", js) works with Firefox and IE8, but not IE6/7.
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return is code passed to eval().
Anyone has a suggestion on to set the onclick attribute to to make this work for Firefox and IE 6/7/8? Also see below the code I used to test this.
<html>
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var js = "alert('B'); return false;";
// Set with JQuery: doesn't work
$("a").attr("onclick", js);
// Set with setAttribute(): at least works with Firefox
//document.getElementById("anchor").setAttribute("onclick", js);
});
</script>
</head>
<body>
Click
</body>
</html>
You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()
$(document).ready(function(){
var js = "alert('B:' + this.id); return false;";
// create a function from the "js" string
var newclick = new Function(js);
// clears onclick then sets click using jQuery
$("#anchor").attr('onclick', '').click(newclick);
});
That should cancel the onClick function - and keep your "javascript from a string" as well.
The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.
You also said:
Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().
No - it won't, but onclick = eval("(function(){"+js+"})"); will wrap the 'js' variable in a function enclosure. onclick = new Function(js); works as well and is a little cleaner to read. (note the capital F) -- see documentation on Function() constructors
BTW, without JQuery this could also be done, but obviously it's pretty ugly as it only considers IE/non-IE:
if(isie)
tmpobject.setAttribute('onclick',(new Function(tmp.nextSibling.getAttributeNode('onclick').value)));
else
$(tmpobject).attr('onclick',tmp.nextSibling.attributes[0].value); //this even supposes index
Anyway, just so that people have an overall idea of what can be done, as I'm sure many have stumbled upon this annoyance.
One gotcha with Jquery is that the click function do not acknowledge the hand coded onclick from the html.
So, you pretty much have to choose. Set up all your handlers in the init function or all of them in html.
The click event in JQuery is the click function $("myelt").click (function ....).
just use jQuery bind method !jquery-selector!.bind('event', !fn!);
See here for more about events in jQuery
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href attribute of the anchor like so:
Click me
Note that following gnarf's idea you can also do:
var js = "alert('B:' + this.id); return false;";<br/>
var newclick = eval("(function(){"+js+"});");<br/>
$("a").get(0).onclick = newclick;
That will set the onclick without triggering the event (had the same problem here and it took me some time to find out).
Came up with a quick and dirty fix to this. Just used <select onchange='this.options[this.selectedIndex].onclick();> <option onclick='alert("hello world")' ></option> </select>
Hope this helps