I'm having trouble getting the javascript .focus() function to work. At this point, I'm really not sure why it's failing to execute. Could it have something to do with onload?
This is my code:
var request_brochure = function()
{
var name = $("name").value;
var email = $("email").value;
var isValid = true;
if(name == "")
{
$("name").focus();
alert("Please fill in your name.");
$("name").focus();
isValid = false;
}
else if(email == "")
{
window.setTimeout(function(){$("email").focus();}, 100);
alert("Please fill in your email. ");
window.setTimeout(function(){$("email").focus();}, 100);
isValid = false;
}
if(isValid)
{
$("form_b").submit();
//$("brochure").innerHTML = "Request Submitted";
}
}
window.onload = function () {
$("name").focus();
$("submit1").onclick = request_brochure;
}
var $ = function (id) {
return document.getElementById(id);
}
Any help is appreciated
I suspect the event isn't binding correctly. window.onload does not ensure the element with id submit_1 is loaded. try adding the event to the button directly:
<input id="submit_1" onclick="request_brochure()" />
if that works then your problem is just that. Without jQuery you could mostly get away with binding the event by putting $("submit1").onclick = request_brochure; in a <script> at the end of the page, but results will be mixed from browser to browser. I'd really recommend using jQuery(function () { $("submit1").onclick = request_brochure; }) and leaving the heavy lifting of determining when the page is completely loaded to the library, since it's been tried and tested for years and is much less likely to fail than a native approach.
The comments on your question have a lot of truth, and I'd hate to see you go down the path of jQuery's high level stuff designed to make non-programmers and programmers with little javascript knowledge live's easier. With that said, the browser landscape is quite the jungle, with more than half of the world on IE 8 or lower (I could be wrong about that by now, but I'm sure it's still a considerable amount), jQuery's low level stuff (like $.ajax, $(function () {}) and the sizzle selector engine) is indispensable in my opinion. The main purposes of these utilities (jQuery's low level functions) is to address browser fragmentation issues and make devs live's easier. It's good to know the underlying code, but I'll take $.ajax over any implementation of HttpXmlRequest in a heartbeat (I still remember the days of IE6's activeX component... those were dark times). just don't do $('#some-form-field').val() without first learning document.getElementById('some-form-field').value and you should be fine :)
Related
I'm working on a responsive site with a specific set of jQuery functions for the desktop layout and mobile layout. They interfere with each other if they're both active at the same time.
By checking window.width, I'm able to deliver only the correct set of functions on page load, and I'd like to do the same on window.resize.
I've set up a stripped down Fiddle of where I'm at here: http://jsfiddle.net/b9XEj/
Two problems exist right now:
Either desktopFunctions or mobileFunctions will continuously fire on page resize, whether they have already been loaded or not.
If the window is resized beyond one breakpoint and then returned to the previous size, the incorrect set of functions will already have been loaded, interfering with the current set.
The window.resize function should behave in the following way:
Check if the correct set of functions currently active for the viewport size
If yes, return.
If no, fire correct set of functions and remove incorrect set of functions if they exist.
In the Fiddle example above, you would always see a single line, displaying either "Mobile Functions are active" or "Desktop Functions are active".
I'm a bit lost at this point, but I have tried using
if ($.isFunction(window.mobileFunctions))
to check if functions already exist, but I can't seem to get it working without breaking the overall function. Here's a fiddle for that code: http://jsfiddle.net/nA8TB/
Thinking ahead, this attempt also wouldn't take into account whether the incorrect set of functions exists already. So, I'm really hoping there's a way I can deal with this in a simpler way and solve both problems.
Any help would be much appreciated!
Following conquers 2 of the problems. The resize fires many times a second, so using a timeout will fix it firing your code constantly. It also adds a check to see if the same size is in effect, and return if it is
$(document).ready(function() {
var windowType;
var $wind = $(window);
var desktopFunctions = function() {
$('body').append('<p>Desktop functions are active</p>');
}
var mobileFunctions = function() {
$('body').append('<p>Mobile Functions are active</p>');
}
var mobileCheck = function() {
var window_w = $wind.width();
var currType = window_w < 940 ? 'mobile' :'desktop';
if (windowType == currType) {
$('body').append('<p>No Type Change, Width= '+window_w+'</p>');
return;
} else {
windowType = currType;
}
if (windowType == 'mobile') {
mobileFunctions();
} else {
desktopFunctions();
}
}
mobileCheck();
var resizeTimer;
$wind.resize(function() {
if (resizeTimer) {
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(mobileCheck, 300)
});
});
DEMO: http://jsfiddle.net/b9XEj/1/
Without seeing some real world differences between your 2 sets of functions it is hard to provide gudance on how to stop them conflicting. One possibility is checking the windowType in your functions
You can prevent the continuous firing by adding a delay mobileCheck. Use a setTimeout along with a checkPending boolean value.
var checkPending = false;
$(window).resize(function(){
if (checkPending === false) {
checkPending = true;
setTimeout(mobileCheck, 1000);
}
});
See here: http://jsfiddle.net/2Q3pT/
Edit
As far as the second requirement, you could use this pattern to create or use the existing one:
mobileFunctions = mobileFunctions || function() {
// mobile functions active
};
See: http://jsfiddle.net/2Q3pT/2/
I have not a good Javascript knowledge, but I'm kinda good with jQuery though. I want to change some jQuery code to pure Javascript, but I have no idea how to do it.
$(document).ready(function()
{
$('#block').one('click', function()
{
$(this).val('{L_SEND_CONFIRM}').removeClass('button1');
$('#replacement').val('{L_BLOCK_CODE}');
});
});
Anyone willing to help me out please?
P.S: Sorry for asking such a dumb question, I really need to learn Javascript myself ASAP.
This is a rough equivalent (there are subtleties that if you want to address start getting annoying, thus the need for frameworks in the first place):
window.onload = function() {
document.getElementById('block').onclick = function() {
this.onclick = '';
this.value = '{L_SEND_CONFIRM}';
this.className = this.className.replace('button1','');
document.getElementById('replacement').value = '{L_BLOCK_CODE}';
}
}
onready and onload are two different beasts.
onready fires when the DOM is ready, but graphics may not have been loaded yet.
onload fires when everything needed, including graphics, have finished.
I like this library here to handle the onready stuff. It uses DOM methods for browsers that support it and uses a weird IE hack when it must:
https://github.com/ded/domready
I am new to jQuery and javascript and I am used mainly to php. I am upgrading my site so it contains a little ajax to improve usability and to keep me busy!
I am using this simple little script I threw together for the login page. All works well at the minute but I have a couple of questions I'd like to ask!
$('#loginForm .submit').click(function(event) {
$('.error').hide();
event.preventDefault();
var errors = 0;
var loginEmail = $('#loginEmail').val();
var loginPassword = $('#loginPassword').val();
if (loginEmail.length == 0) {
$('#loginEmail').after('<div class="error"></div>');
errors++;
}
if (loginPassword.length == 0) {
$('#loginPassword').after('<div class="error"></div>');
errors++;
}
if (!errors) {
$('.submit').submit();
}
});
You will notice that the first line of code within the function is;
$('.error').hide();
Now in php I would normally use;
if (isset(........)) {
Is there a simliar way to do this in javascript as when the user first activates the function there will be no html with the class .error?
Also I am trying to add a new parameter to the function as well as the event parameter, how would I do this? I have tried the following?
$('#loginForm .submit').click(function(event, var) {
$('#loginForm .submit').click(function(event var) {
$('#loginForm .submit').click(function('event', 'var') {
And all seem not to work. Then again I am going by php, jQuery/javascript is not my strong point!
Thanks
Before performing an action, you can check if the function $() selected element by using the following syntax:
if ($('.error').length)
{
// actions
}
If the .error - div exists in the DOM by default and is just hidden, you can't just check the length of $('.error'), because even if it's empty, length will return 1.
You could do something like this:
if($('.error').html().length !== 0){
//do something
}
This will check the containing string of the error-div, so if it's empty, length will return 0.
Still I would recommend setting a boolean var. If errors occur, it gets set to false and you can check the var and you do not have to query for DOM-elements for such a simple task.
To your second question, try something like this:
$('#loginForm .submit').bind("click", {variable1: var}, handleSubmit);
function handleSubmit(event){
var passedVar = event.data.variable1;
}
The other day I posted about a Flash/Javascript issue I was having. Please see this:
Issues with javascript properly loading and seeing everything
I know how I want to fix it, but I am not in any way shape or form familiar with actionscript. I have avoided adobe products like the plague from when I was developing myself since it costs a fortune to buy and of their products, but big employers love it and pay for it so here I am. Our "Flash" guy just left the team and I inherited this issue. If you read my other post you know what is going on so I will move on. I want to make a simple call from actionscript to my javascript taht is referenced in my other post. I specifically want to call the CheckboxCollection function from inside of actionscript. I don't need to pass it any args or anything of the such from inside of actionscript. All I need it to do is run that function once the flash is done loading. The javascript function will take care of everything I need, I just HAVE TO HAVE IT called from actionscript to make everything work in harmony. I am in the middle of teaching myself all things adobe and actionscript(much to my dismay), but I really have no clue where top go from here to make this work. I have reviewed adobe documentation, but until I have a better grasp of the language as a whole I am still lost. I copied most of my actionscript on to here, but I did leave out everything that had to deal with mouseover events, since my issue is not about a mouseover and they all work like a charm. Thanks in advance!
-------------------------------------------------------------------------------------------UPDATE: I had to stop working on this to get some other things done, but I am back to step one. NO matter what I do I am having no luck making this work. I have tried all suggestions on here, and tried everything I KNOW how to do, but I am having no luck. If anyone could take a look at this post and the one that I link to (It is the companion javascript for this) and see if they can come up with anything. I have tried so many different iterations of my code there is no use putting all of my trials up for example of what doesn't work, Thanks Everyone!
/*
JavaScript External Calls
*/
function RegisterExternalCalls():void
{
if(ExternalInterface.available)
ExternalInterface.addCallback("HighlightWheel", HighlightWheel);
}
function HighlightWheel($args:String,$show:String,...arguments):void
{
$args = $args == "financial"?"center":$args;
var _obj:Object = ObjectCollection[$args].Objects.Click;
if(ObjectCollection[$args].Objects.currentObject.name.toLowerCase() == "center")
{
bcenter = true;
_obj = ObjectCollection[$args].Objects.currentObject.getChildByName("financialBtn");
}
if(CBool($show))
{
if(arguments.length > 0 && arguments[0] == "TITLE") // || $args == "center")
_obj.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OVER));
else
{
if(ObjectCollection[$args].labels.Label.toUpperCase() === "CENTER")
{
ObjectCollection["income"].Objects.Click.gotoAndPlay(2);
ObjectCollection["property"].Objects.Click.gotoAndPlay(2);
ObjectCollection["education"].Objects.Click.gotoAndPlay(2);
ObjectCollection["health"].Objects.Click.gotoAndPlay(2);
ObjectCollection["retirement"].Objects.Click.gotoAndPlay(2);
}
else
{
_obj.gotoAndPlay(2);
}
}
}
else
{
if(arguments.length > 0 && arguments[0] == "TITLE")
_obj.dispatchEvent(new MouseEvent(MouseEvent.MOUSE_OUT));
else
{
if(ObjectCollection[$args].labels.Label.toUpperCase() === "CENTER")
{
ObjectCollection["income"].Objects.Click.gotoAndPlay(11);
ObjectCollection["property"].Objects.Click.gotoAndPlay(11);
ObjectCollection["education"].Objects.Click.gotoAndPlay(11);
ObjectCollection["health"].Objects.Click.gotoAndPlay(11);
ObjectCollection["retirement"].Objects.Click.gotoAndPlay(11);
}
else
{
_obj.gotoAndPlay(11);
}
}
}
}
function CallExternalFunction($label:String,$show:Boolean = true):void
{
var lbl:String = $label.toLowerCase().indexOf("btn") > -1?"financialTitle":$label + "Title";
if(ExternalInterface.available)
ExternalInterface.call("COUNTRY.Financial.highlightProductGroup",lbl,$show);
}
function CBool($value:String):Boolean
{
if($value == "true")
return true;
else
return false;
}
function PrintSetup($evt:MouseEvent):void
{
var pjob:PrintJob = new PrintJob();
if(pjob.start())
{
pjob.addPage(wheel);
pjob.send();
}
}
I believe you do this through ExternalInterface.call and pass the javascript function that should be called, like so:
ExternalInterface.call( "CheckboxCollection" )
If you need to pass arguments:
ExternalInterface.call( "CheckboxCollection", value1, value2 )
For more information here is the documentation
If in your JS you don't need necessarily this:
var CheckboxCollection = function()
try to change it to this:
function CheckboxCollection()
even if it seems (if the JS is still the same) you have anything nested. Maybe you can try too call it this way to (but I never tried anything similar):
ExternalInterface.call("SOME.PLACE.QuoteRequest.CheckboxCollection");
I was trying to make a javascript gallery script by my own.
When i have done with it i was pretty happy, until i noticed, that it doesn't work in IE6.
In FireFox everything looks fine. So i started debugging.
I noticed, that setAttribute is one of the problems for sure. Maybe even the biggest.
So after viewing an interetsing article about setting onclick property with parameters i was kind of happy, but one thing stayed unsolved for me. Using callback method is tricky, but i just don't know how to pass event object that way. Here is the old code sample:
var miniatury = document.getElementsByTagName ("a");
function zoom (){
for (l = 0; l < miniatury.length; l++) {
if (miniatury[l].className.match("zoom") != null ) {
var href = miniatury[l].href;
if (document.images) {
preImg[l] = new Image();
preImg[l].src = href;
miniatury[l].setAttribute("onclick", "przybliz(preImg["+[l]+"].src, event); event.returnValue=false; return false;");
}
else {
miniatury[l].setAttribute("onclick", "przybliz(href, event); event.returnValue=false; return false;");}
}
}
}
function przybliz(adres, event) {
pojemnik.style.display = 'block';
if (navigator.appName == "Microsoft Internet Explorer") {
pozycjaX= window.event.clientX + document.documentElement.scrollLeft
+ document.body.scrollLeft;
pozycjaY= window.event.clientY + document.documentElement.scrollTop
+ document.body.scrollTop;
}
if (navigator.appName != "Microsoft Internet Explorer") {
pozycjaX = event.clientX + window.scrollX;
pozycjaY = event.clientY + window.scrollY;
}
pojemnik.style.top = pozycjaY+'px';
pojemnik.style.left = pozycjaX+'px';
Question is:
How to change the code into
onclick = callback(f, arguments)
with passing event object values, and having the luxury to use them later ?
Well, doing it with jQuery:
$(miniatury[l]).bind("click", preImg[l], przybliz);
After which you could retrieve it in the function:
function przybliz(evt) {
var adres = evt.data;
//...
}
Without jQuery it becomes a bit more difficult, since you might have to store the value in a closure, which unless you're careful can force the whole scope chain to stay in memory (not a good thing).
The best way is to just append a handler to it. eg:
if (minitury.attachEvent) {
minitury.attachEvent("onclick", callback);
} else {
minitury.addEventListener("click", callback, false);
}
Where callback is a function with a single parameter. Like below:
function callback(evt) {
if (! evt) evt = window.event;
<insert other code here>
}
This should be what you're looking to do.
EDIT: I realized you were asking how to send parameterized callbacks. I doubt there is a good cross-browser method of doing this, but you could get around that by adding a custom attribute to the element in question which holds your data and through the event object (either evt.target or evt.srcElement) you can access the element. Make sure to follow the guidelines set by the w3c for custom attributes. w3c custom attributes
IE6 is pretty bad that way. Getting familiar with raw JS is essential, but ultimately you won't want to be bothered with making all kinds of accommodations for the little differences between browsers.
Antony Mills shows you how easy a framework (like jQuery or prototype) can make your life. Another key thing about frameworks is that they have usually thought long and hard about all of these cross browser issues so that you don't have to.