So, I use jQuery quite extensively and I am well aware of the "right" way to do the below, but there are times where I want to solve it in a more generic way. I'll explain.
So, I may have a link, like this: <a href='menu' class='popup'>Show menu</a>. Now, I have a jQuery function that fires on click for all a.popup that takes the href-attribute and shows the <div id='menu'></div> item (in this case). It also handles URL's if it can't find a DOM item with that ID.
No problem here. But, there are times when I don't have the same control over the coe where I can create a selectable target that way. Either because the code isn't created by me or because it is created through a chain of function that would all need a huge ovrhaul which I won't do.
So, from time to time, I would like to have this code:
Show menu
This would be in a case where I can only submit the label and the HREF for a link. No class, no nothing.
Problem here is that the function popup() has no idea about what element invoked it, and in most cases that's not a problem for me, since I only need to know where the mouse cursor was upon invokation.
But in some cases, I use someone elses jQuery functions, like qTip or something else. so I still want to fire off qTip(); when clicking a link that runs this JS function, but what do I attach it to to make it show? I can't just runt $().qTip(); because that implies $(this) and "this" is undefined inside the function.
So how do I do it? Any ideas?
Is there anyway you change the javascript method to javascript:popup('menu', this);? I've used this method successfully many times.
Instead of referring to "this" try referring to $('a:focus') to refer to the link that was clicked.
Here's a quick and, as #Crescent Fresh would add, dirty (☺) sample:
<body>
<p>Show popup()</p>
<div id="menu" style="display:none">Today's menu</div>
<script type="text/javascript">
function popup(elm) {
$('#' + elm).show();
alert( $('a:focus').text() )
}
</script>
</body>
I tried just ":focus" but IE7 returned too much content. I tested this in FF 3.6.3, IE7, Chrome 4.1.249.1064 (all on Windows) and it seems OK, but I see now (when I was just about to hit "Post Your Answer") this relies on the browser's native support for querySelectorAll - see this jQuery Forum post ":focus selector filter?" and the jQuery.expr entry in the jQuery Source Viewer (where it appears Paul's idea was not implemented).
How about
Show menu
Once you get the event object you can virtually do anything to it.
Related
I am trying to use an HTML button to call a JavaScript function.
Here's the code:
<input type="button" value="Capacity Chart" onclick="CapacityChart();">
It doesn't seem to work correctly though. Is there a better way to do this?
Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.
There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.
1: There's defining it in the HTML:
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
2: There's adding it to the DOM property for the event in Javascript:
//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
3: And there's attaching a function to the event handler using Javascript:
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.
The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.
Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:
CapacityWindow.document.write(s);
Try the following instead:
CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.
I would say it would be better to add the javascript in an un-obtrusive manner...
if using jQuery you could do something like:
<script>
$(document).ready(function(){
$('#MyButton').click(function(){
CapacityChart();
});
});
</script>
<input type="button" value="Capacity Chart" id="MyButton" >
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value
This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code
Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)
One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.
Your code is failing on this line:
var RUnits = Math.abs(document.all.Capacity.RUnits.value);
i tried stepping though it with firebug and it fails there. that should help you figure out the problem.
you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>
So, here's a script that I've written to make some inputs dependent on an affirmative answer from another input. In this case, the 'parent' input is a radio button.
You can see that it hides parent divs of inputs when the document is ready, and then waits for the pertinent option to be changed before firing the logic.
If you'll look at the comment near the bottom of the javascript, you'll see what's been stumping me. If I remove the if statement, the change function does not fire. If I set the variable so that there is not an error logged in the console, then the change event does not fire.
If I change the jquery selector to $('select').change... the event fires, but obviously won't work on a radio button. Changing it to $('input').change... also fails.
<script type="text/javascript"><!--
$(function(ready){
$('#input-option247').parent().hide();
$('#input-option248').parent().hide();
$('#input-option249').parent().hide();
$('#input-option250').parent().hide();
$('#input-quantity').attr('type', 'hidden');
$('#input-quantity').parent().hide();
$('input[name="option\\[230\\]"]').change(function() {
if (this.value == '21') { //If yes, display dependent options
$('#input-option247').parent().show().addClass('required');
$('#input-option248').parent().show().addClass('required');
$('#input-option249').parent().show().addClass('required');
$('#input-option250').parent().show().addClass('required');
} else if (this.value == '22') { //If no, hide dependent options
$('#input-option247').parent().hide().removeClass('required');
$('#input-option248').parent().hide().removeClass('required');
$('#input-option249').parent().hide().removeClass('required');
$('#input-option250').parent().hide().removeClass('required');
}
});
//I don't know why this is necessary, but the input.change() event WILL NOT FIRE unless it's present. If I set the variable, then it breaks the change function above. If it's not here, it breaks the change function above. I'm stumped.
if(poop){}
});//--></script>
I'm really hoping that someone will see something rather obvious that my tired brain won't see. This is such a simple script, and I'm pulling my hair out over what seems like a rather annoying bug.
If you selector has special characters you need to use \\ before those characters.
$('input[name="option[230]"]')
should be
$('input[name="option\\[230\\]"]')
See http://api.jquery.com/category/selectors/
This may or may not be a good answer, but I managed to get the problem solved. I have another script on the page that is firing on the change event using this selector: $('select[name^="option"], input[name^="option"]').change(function() {
My best guess is that both functions cannot fire using a single change event from the same element. I moved the functional part of the code above to be within the second script, and it seems to be working as expected. If anyone wishes to contribute an answer that explains this behavior, I will accept it.
I'm trying to automate clicking a few links on a webpage
For example, in Google Chrome if I type Javascript:setDisplayType('source'); then it runs the function in the html defined as
<input type="radio" name="DisplayType" value="source"
onclick="setDisplayType('source');">
So far so good. However, I'm unsure about how to do the same with the following
<td id="4124321351_U923" class="o bgc b" onclick="s(this,'329803656','40745906','9/2');b(this,'5.5','5.5');">5.5</td>
I've tried the following without success
Javascript:s(this,'329803656','40745906','9/2');
Javascript:b(this,'5.5','5.5');
Javascript:s(this,'329803656','40745906','9/2');b(this,'5.5','5.5');
Please can someone explain why it's not working and how to fire this onclick event using a similar method?
if you're not using JQuery or similar, then something like:
document.getElementById("4124321351_U923").click();
might work. In short, your examples above don't work because the 'this' magic variable needs to be initialised to point to the link being clicked. You could either try to initiate a click event on the element (as per my example) or you could manually grab a reference to the link, and pass that in instead of this
Problem is with this argument because it's not called from the element and you called it outside.
Javascript:s(this,'329803656','40745906','9/2');
Try proving a proper argument like this,
Javascript:s(document.getElementById('4124321351_U923'),'329803656','40745906','9/2');
I'm modifying some code from a question asked a few months ago, and I keep getting stymied. The bottom line is, I hover over Anchors, which is meant to fade in corresponding divs and also apply a "highlight" class to the Anchor. I can use base JQuery and get "OK" results, but mouse events are making the user experience less than smooth.
I load JQuery 1.3 via Google APIs.
And it seems to work. I can use the built in hover() or mouseover(), and fadeIn() is intact... no JavaScript errors, etc. So, JQuery itself is clearly "loaded". But I was facing a problem that it seemed everyone was recommending hoverIntent to solve.
After loading JQuery, I load the hoverIntent JavaScript. I've triple-checked the path, and even dummy-proofed the path. I just don't see any reasonable way it can be a question of path.
Once the external javascripts are (allegedly) loaded in, I continue with my page's script:
var $old=null;
$(function () {
$("#rollover a").hoverIntent(doSwitch,doNothing)
});
function doNothing() {};
function doSwitch() {
var $this = $(this);
var $index = $this.attr("id").replace(/switch/, ""); //extract the index number of the ID by subtracting the text "switch" from its name
if($old!=null) $old.removeClass("highlight"); //remove the highlight class from the old (previous) switch before adding that class to the next
$this.addClass("highlight"); //adds the class "highlight" to the current switch div
$("#panels div").hide(); //hide the divs inside panels
$("#panel" + $index).fadeIn(300); //show the panel div "panel + number" -- so if switch2 is used, panel2 will be shown
$old = $this; //declare that the current switch div is now "old". When the function is called again, the old highlight can be removed.
};
I get the error:
Error: $("#rollover a").hoverIntent is not a function
If I change to a known-working function like hover (just change ".hoverIntent" to ".hover") it "works" again. I'm sure this is a basic question but I'm a total hack when it comes to this (as you can see by my code).
Now, for all appearances, it SEEMS like either the path is wrong (I've zillion-checked and even put it on an external site with an HTTP link that I double-checked; it's not wrong), or the .js doesn't declare the function. If it's the latter, I must be missing a few lines of code to make the function available, but I couldn't find anything on the author's site. In his source code he uses a $(document).ready, which I also tried to emulate, but maybe I did that wrong, too.
Again, the weird bit is that .hover works fine, .hoverIntent doesn't. I can't figure out why it's not considered a function.
Trying to avoid missing anything... let's see... there are no other JavaScripts being called. This post contains all the Javascript the page uses... I tried doing it as per the author's var config example (hoverIntent is still not a function).
I get the itching feeling I'm just missing one line to declare the function, but I can't for the life of me figure out what it is, or why it's not already declared in the external .js file. Thanks for any insight!
Greg
Update:
The weirdest thing, since I'm on it... and actually, if this gets solved, I might not need hoverIntent solved:
I add an alert to the "doNothing" function and revert back to plain old .hover, just to see what's going on. For 2 of my 5 Anchors, as soon as I hover, doNothing() gets called and I see the alert. For the other 3, doNothing() correctly does NOT get called until mouseout. As you can see, the same function should apply for any Anchor inside of "rollover" div. I don't know why it's being particular.
But:
If I change fadeIn to another effect like slideDown, doNothing() correctly does NOT get called until mouseout.
when using fadeIn, doNothing() doesn't get called in Opera, but seems to get called in pretty much all other browsers.
Is it possible that fadeIn itself is buggy, or is it just that I need to pass it an appropriate callback? I don't know what that callback would be, if so.
Cheers for your long attention spans...
Greg
Hope I didn't waste too many people's time...
As it turns out, the second problem was 2 feet from the screen, too. I suspected it would have to do with the HTML/CSS because it was odd that only 2 out of 5 elements exhibited strange behaviour.
So, checked my code, dug out our friend FireBug, and discovered that I was hovering over another div that overlapped my rollover div. Reason being? In the CSS I had called it .panels instead of .panel, and the classname is .panel. So, it used defaults for the div... ie. 100% width...
Question is answered... "Be more careful"
Matt and Mak forced me to umpteen-check my code and sure enough I reloaded JQuery after loading another plugin and inserting my own code. Since hoverIntent modifies JQuery's hover() in order to work, re-loading JQuery mucked it up.
That solved, logic dictated I re-examine my HTML/CSS in order to investigate my fadeIn() weirdness... and sure enough, I had a typo in a class which caused some havoc.
Dumb dumb dumb... But now I can sleep.
I am trying to use an HTML button to call a JavaScript function.
Here's the code:
<input type="button" value="Capacity Chart" onclick="CapacityChart();">
It doesn't seem to work correctly though. Is there a better way to do this?
Here is the link:http://projectpath.ideapeoplesite.com/bendel/toolscalculators.html click on the capacity tab in the bottom left section. The button should generate an alert if the values are not changed and should produce a chart if you enter values.
There are a few ways to handle events with HTML/DOM. There's no real right or wrong way but different ways are useful in different situations.
1: There's defining it in the HTML:
<input id="clickMe" type="button" value="clickme" onclick="doFunction();" />
2: There's adding it to the DOM property for the event in Javascript:
//- Using a function pointer:
document.getElementById("clickMe").onclick = doFunction;
//- Using an anonymous function:
document.getElementById("clickMe").onclick = function () { alert('hello!'); };
3: And there's attaching a function to the event handler using Javascript:
var el = document.getElementById("clickMe");
if (el.addEventListener)
el.addEventListener("click", doFunction, false);
else if (el.attachEvent)
el.attachEvent('onclick', doFunction);
Both the second and third methods allow for inline/anonymous functions and both must be declared after the element has been parsed from the document. The first method isn't valid XHTML because the onclick attribute isn't in the XHTML specification.
The 1st and 2nd methods are mutually exclusive, meaning using one (the 2nd) will override the other (the 1st). The 3rd method will allow you to attach as many functions as you like to the same event handler, even if the 1st or 2nd method has been used too.
Most likely, the problem lies somewhere in your CapacityChart() function. After visiting your link and running your script, the CapacityChart() function runs and the two popups are opened (one is closed as per the script). Where you have the following line:
CapacityWindow.document.write(s);
Try the following instead:
CapacityWindow.document.open("text/html");
CapacityWindow.document.write(s);
CapacityWindow.document.close();
EDIT
When I saw your code I thought you were writing it specifically for IE. As others have mentioned you will need to replace references to document.all with document.getElementById. However, you will still have the task of fixing the script after this so I would recommend getting it working in at least IE first as any mistakes you make changing the code to work cross browser could cause even more confusion. Once it's working in IE it will be easier to tell if it's working in other browsers whilst you're updating the code.
I would say it would be better to add the javascript in an un-obtrusive manner...
if using jQuery you could do something like:
<script>
$(document).ready(function(){
$('#MyButton').click(function(){
CapacityChart();
});
});
</script>
<input type="button" value="Capacity Chart" id="MyButton" >
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById(), it should probably work. Example: document.getElementById("RUnits").value instead of document.all.Capacity.RUnits.value
This looks correct. I guess you defined your function either with a different name or in a context which isn't visible to the button. Please add some code
Just so you know, the semicolon(;) is not supposed to be there in the button when you call the function.
So it should just look like this: onclick="CapacityChart()"
then it all should work :)
One major problem you have is that you're using browser sniffing for no good reason:
if(navigator.appName == 'Netscape')
{
vesdiameter = document.forms['Volume'].elements['VesDiameter'].value;
// more stuff snipped
}
else
{
vesdiameter = eval(document.all.Volume.VesDiameter.value);
// more stuff snipped
}
I'm on Chrome, so navigator.appName won't be Netscape. Does Chrome support document.all? Maybe, but then again maybe not. And what about other browsers?
The version of the code on the Netscape branch should work on any browser right the way back to Netscape Navigator 2 from 1996, so you should probably just stick with that... except that it won't work (or isn't guaranteed to work) because you haven't specified a name attribute on the input elements, so they won't be added to the form's elements array as named elements:
<input type="text" id="VesDiameter" value="0" size="10" onKeyUp="CalcVolume();">
Either give them a name and use the elements array, or (better) use
var vesdiameter = document.getElementById("VesDiameter").value;
which will work on all modern browsers - no branching necessary. Just to be on the safe side, replace that sniffing for a browser version greater than or equal to 4 with a check for getElementById support:
if (document.getElementById) { // NB: no brackets; we're testing for existence of the method, not executing it
// do stuff...
}
You probably want to validate your input as well; something like
var vesdiameter = parseFloat(document.getElementById("VesDiameter").value);
if (isNaN(vesdiameter)) {
alert("Diameter should be numeric");
return;
}
would help.
Your code is failing on this line:
var RUnits = Math.abs(document.all.Capacity.RUnits.value);
i tried stepping though it with firebug and it fails there. that should help you figure out the problem.
you have jquery referenced. you might as well use it in all these functions. it'll clean up your code significantly.
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>