Javascript Syntax Error - javascript

var dayNumberCell = doc.createElement('td');
dayNumberCell.className = 'days_link';
dayNumberCell.setAttribute('onclick', function(scope) {
var bindScope = function() {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
};
return bindScope;
}(this));
The above code generates tds onclick event listener. and the generated code looks like
<td class="days_link" onclick="function () {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);
}">15</td>
By clicking on TD I get syntax error message.
How should I write my function that the specified code executes and also have no syntax error.
Thanks in advance.

You put your function definition inside a string literal. It's expecting code and all it has is text.

You should rewrite your onclick handler as follows:
dayNumberCell.onclick = function(e) {
var target = e.target || e.srcElement;
target.changeDate(target, target.id);
target.returnDate(target.month, target.year);
return false;
};
I don't understand why you would try to set the inline click handler from an external js file. You took the right step to remove inline click handlers from your html, but when you set the click handler from an external script, you should not be setting the onclick attribute.
In addition to the way I highlighted, you could use the w3c and microsoft event handlers so that you can attach multiple onclick events to the same element. However, this is a more complicated approach since different browsers handle it differently. This will suffice as long as you don't plan to have other onclick handlers attached to the same cell.

<td class="days_link" onclick="function () {
scope.changeDate(this, this.id);
scope.returnDate(scope.month, scope.year);}">15</td>
Have you tried outside the function?
<td class="days_link" onclick="scope.changeDate(this, this.id);scope.returnDate(scope.month, scope.year);">15</td>
if that don't work, try it on your javascript file, and there, yes, with a function.

Perhaps you would prefer not to use any javascript libraries, but I would highly recommend using the YUI Event utility for this.
Dustin Diaz has a great article that explains how it would simplify this for you.
http://www.dustindiaz.com/yahoo-event-utility/

Related

Printing inner HTML of clicked elements to the console

I want to be able write code in the console that allows me to print to the console the inner HTML of any elements I click on within a Web page. This is my code so far.
var findBody = document.querySelector ('body');
function findContent(event) {
findBody.onclick = "findContent(event)";
console.log (event.target.innerHTML);
}
Please be kind, I'm just beginning to write JS. Thanks
You've found body element and written a function. But your function is never called, you have to make browser execute it when event (click) happens.
Basic way to attach event handler is to define on+eventName attribute of the element. Still, it is better to use element.addEventListener method, because you can add as many event listeners to the same element as you want. Also, this method allows to control when event handler is applied during event propagation through the document (nice doc)
Here's basic solution:
// find body element
var findBody = document.querySelector('body');
// define handler function
function findContent(event) {
console.log (event.target.innerHTML);
}
// attach event handler
findBody.addEventListener('click', findContent);
This should work:
var findBody = document.querySelector ('body');
function findContent(event) {
console.log (event.target.innerHTML);
}
findBody.onclick = findContent;
Maybe, You can try this snippet:
function find() {
console.log(event.target.innerHTML);
}
document.onclick = find;

Add Javascript function with javascript

I want to add an event trigger (onClick) with javascript dynamically.-at runtime.
I have a dynamic count of buttons, and on each button click, I need a specific javascript function.
I have the idea to add the javascript functions with javascript.
I tried that with some example:
document.getElementById("trigger").innerHTML = "<script type=\"text/javascript\">function testal() { alert(\"trigger\"); }<\/script>";
if i press on the button with the onClick="testal()":
Error Message: "is undefined"
innerHTML is Not JavaScript.
Indeed that causes a scription injection.
document.getElementById("trigger").onclick = testal;
function testal() { alert('trigger'); }
In case you do not know beforehand what event you'd like to register the handler for (onclick, onkeydown, onkeypress etc) you can do:
var event_type = 'onclick';
document.getElementById('trigger')[event_type] = testal;
See also http://www.quirksmode.org/js/events_tradmod.html
I think you want to use jquery .on method. Try this
$(document).off('click', 'button');
$(document).on('click', 'button', function() {
alert('Executed');
});
If you do not know which event handler to be registered with button click, you can write your logic inside the anonymous handler.
I solved it with
$("#trigger").html("<script type=\"text/javascript\">function testal() { alert(\"trigger\"); }<\/script>");

What is the jQuery or javaScript syntax to make functions work only on the active/focused input/button/text area?

I am a beginner & self interested web coder.
I have been testing, asking, retesting, trying, reading up on different functionality solutions in javaScript to an online form which will consist of a multitude of <textarea>'s once I am done.
I am fairly ok, with the current state of functions, which are based upon several js events. Example code would be (written funny so it is easier to read in the forum, actual code is one line obviously):
<textarea
data-id="0"
class="classOne classTwo"
id="dataInput_0"
name="xInput_row_1"
onFocus="functionOne();"
onBlur="functionTwo();"
onKeyUp="functionThree();">
</textarea>
I built and tested all the functions to work specifically on the id="dataInput_0" using getElementById. Example:
var d = document.getElementById("dataInput_0");
So my question is how to I make the functions trigger for other "dataInput" id's?
In other words:
var d = document.getElementById('whichever dataInput that is active/focused');
Thanks!
The simplest way to work with your current code would be to do this:
onFocus="functionOne(this);"
...and then define your function:
function functionOne(el) {
// el is the element in question, used e.g.:
alert(el.name);
}
Within the onFocus=... the browser sets this to the element in question, so you can then pass it as a parameter to your function. Your function then just uses it directly rather than having to go via getElementById().
But since you mentioned jQuery, you could remove the inline onFocus and other onXYZ handlers from your html and just do it all in your JS as follows:
$("textarea").focus(function() {
// here this is the element in question, e.g.:
alert(this.value);
});
That defines a focus handler for all textareas on the page - to narrow it down to just textareas with class "classOne" do $("textarea.classOne"). Within the function this refers to the focused element. You could use the .blur() and keyup() methods to assign handlers for the other events shown in your code.
My suggestion is to use attribute selector $('input[id^="dataInput_"]') for this and use the jQuery's .on() handler this way:
$('input[id^="dataInput_"]').on({
focus: function{
functionOne($(this));
},
blur: function(){
functionTwo($(this));
},
keyup: function(){
functionThree($(this));
}
});
and the functions:
functionOne(obj){
console.log(obj.val());
}
functionTwo(obj){
console.log(obj.val());
}
functionThree(obj){
console.log(obj.val());
}

Basic jQuery Issues on IE9 (Toggle)

I'm not really a developper. I prefer to design my websites ... So, for my actual project, i must developping some "basic" scripts.
I've met a problem with this:
<script type="text/javascript">
$("button").click(function toggleDiv(divId) {
$("#"+divId).toggle();
});
;
</script>
Into Head-/Head
LINK
<div> id="myContent">Lorem Ipsum</div>
It works for IE8. (Miracle). But not the others browsers...
The idea is that when u click on "LINK" a windows appears and when you click again, the window close.
Any idea ?
Thanks for u time !
One of the problems is you're mixing two different styles of binding event handlers: one of them is good (the jQuery method), the other is bad (the javascript: protocol in your href attribute) - the two don't work together in any way. Another problem is that your selector is completely incorrect (it's looking for a button) for the HTML you've provided (you never create a button).
I'd suggest using a HTML5 data-* attribute to specify the id for the <div> on your <a> element:
LINK
<div id="mycontent">Lorem ipsum</div>
Then use the following jQuery code:
$('a').click(function(e) {
e.preventDefault(); // e refers to the event (the click),
// calling preventDefault() will stop you following the link
var divId = $(this).data('divid');
$('#' + divId).toggle();
});
Note that I've used this in the above code; what this refers to depends on the context in which you use it, but in the context of a jQuery event handler callback function, it will always refer to the element that triggered the event (in this case, your <a> element).
If you extract toggleDiv from the handler, it ought to work. You will probably also need to return false to keep the href from trying to go anywhere.
<script type="text/javascript">
function toggleDiv(divId) {
$("#"+divId).toggle();
return false;
}
</script>

call javascript function on hyperlink click

I am dynamically creating a hyperlink in the c# code behind file of ASP.NET. I need to call a JavaScript function on client click. how do i accomplish this?
Neater still, instead of the typical href="#" or href="javascript:void" or href="whatever", I think this makes much more sense:
var el = document.getElementById('foo');
el.onclick = showFoo;
function showFoo() {
alert('I am foo!');
return false;
}
Show me some foo
If Javascript fails, there is some feedback. Furthermore, erratic behavior (page jumping in the case of href="#", visiting the same page in the case of href="") is eliminated.
The simplest answer of all is...
My link
Or to answer the question of calling a javascript function:
<script type="text/javascript">
function myFunction(myMessage) {
alert(myMessage);
}
</script>
My link
With the onclick parameter...
<a href='http://www.google.com' onclick='myJavaScriptFunction();'>mylink</a>
The JQuery answer. Since JavaScript was invented in order to develop JQuery, I am giving you an example in JQuery doing this:
<div class="menu">
Example
Foobar.com
</div>
<script>
jQuery( 'div.menu a' )
.click(function() {
do_the_click( this.href );
return false;
});
// play the funky music white boy
function do_the_click( url )
{
alert( url );
}
</script>
I prefer using the onclick method rather than the href for javascript hyperlinks. And always use alerts to determine what value do you have.
<a href='#' onclick='jsFunction();alert('it works!');'>Link</a>
It could be also used on input tags eg.
<input type='button' value='Submit' onclick='jsFunction();alert('it works!');'>
Ideally I would avoid generating links in you code behind altogether as your code will need recompiling every time you want to make a change to the 'markup' of each of those links. If you have to do it I would not embed your javascript 'calls' inside your HTML, it's a bad practice altogether, your markup should describe your document not what it does, thats the job of your javascript.
Use an approach where you have a specific id for each element (or class if its common functionality) and then use Progressive Enhancement to add the event handler(s), something like:
[c# example only probably not the way you're writing out your js]
Response.Write("My Link");
[Javascript]
document.getElementById('uxAncMyLink').onclick = function(e){
// do some stuff here
return false;
}
That way your code won't break for users with JS disabled and it will have a clear seperation of concerns.
Hope that is of use.
Use the onclick HTML attribute.
The onclick event handler captures a
click event from the users’ mouse
button on the element to which the
onclick attribute is applied. This
action usually results in a call to a
script method such as a JavaScript
function [...]
I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.
attachEvent / addEventListening allow multiple event handlers to be created.
If you do not wait for the page to be loaded you will not be able to select the element by id. This solution should work for anyone having trouble getting the code to execute
<script type="text/javascript">
window.onload = function() {
document.getElementById("delete").onclick = function() {myFunction()};
function myFunction() {
//your code goes here
alert('Alert message here');
}
};
</script>
<a href='#' id='delete'>Delete Document</a>

Categories