Javascript - Uncaught ReferenceError - Code seems perfect? - javascript

Here's how I'm calling my JS:
"#item.OwnerID#" is a variable from a loop containing an ID. So the element I want to change the CSS for should look like: "cwa123" or some other number for the id...
Here's my JS:
$(document).ready(function() {
function toggleChatControl(id){
var wnd = document.getElementById(id);
if (wnd.style.marginBottom == '-1px') {
wnd.style.marginBottom = '-236px';
} else {
wnd.style.marginBottom = '-1px';
}
}
});
I ain't got a clue, it gives me the "not defined" error...

Out of scope, remove the document ready wrapper
function toggleChatControl(id){
var wnd = document.getElementById(id);
if (wnd.style.marginBottom == '-1px') {
wnd.style.marginBottom = '-236px';
} else {
wnd.style.marginBottom = '-1px';
}
}
Every function creates a new scope, the global scope is window, and that's the scope used for inline javascript.
Inside $(document).ready(function() { ... }); the scope is changed (to document) so the function is out of scope for the inline handler.
An even better approach would be to use a proper event handler
$('.FCChatControl').on('click', function() {
toggleChatControl('cwa#item.OwnerID#');
});

Related

How can I modify an anonymous javascript function with tampermonkey?

Here is the block of code I want to replace:
$(document).ready(function () {
$(".button-purple").click(function () {
interval = $(this).attr('id');
name = $(this.attr('name');
if(Number($(this).val()) === 0) {
if(name == 'static') {
do this
}
else {
do this
}
}
else {
do this
}
});
});
I can't find any documentation on trying to replace the function since it's unnamed though. Is it possible to replace the entire javascript file + delete the line loading it / insert my own script? Would really appreciate any help I can get.
If you just want to remove the click event handler, then simply say
var $element = $(".button-purple");
$element.off('click');
If you want to Remove all the event handlers, then you'll first have to find out what all event handlers are present and then remove them iteratively.
var element = $element[0]; //Make sure the element is a DOM object and not jQuery Object.
// Use this line if you're using jQuery 1.8+
var attachedEvents = $._data(element,'events');
// Use this line if you're using jQuery < 1.8
var attachedEvents = $(element).data('events'); //Here you can also replace $(element) with $element as declared above.
for(var event in attachedEvents){
$element.off(event);
}
UPDATE:
You can simply add your own event handler (using .on() API) after you're done removing all the required existing handlers.
Just define your function.
function yourFunction(){ /* your code */};
$element.on('click', yourFunction);
Update 2:
Since you just want to remove the click event handler, this is the simplest code that will serve your purpose.
$(".button-purple").off('click').on('click', yourFunction);
I'm not aware of tampermonkey, but you can try this:
function chickHandler() {
interval = $(this).attr('id');
name = $(this.attr('name');
if (Number($(this).val()) === 0) {
if (name == 'static') {
do this
} else {
do this
}
} else {
do this
}
}
}
function onReadyHandler() {
$(".button-purple").click(chickHandler);
}
$(document).ready(onReadyHandler);
When you do something like .click(function(){...}), here function is called as a callback. You have to send a function as a callback. Not necessary to be anonymous.

Call function is not a function

$(function() {
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
$.club_settings();
$.club_settings = function() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
})(jQuery);
I got an error that is $.club_settings is not a function. How can i call $.club_settings in a if condition ?
You're defining the function after you call it. Switch around the code like so:
$(function() {
$.club_settings = function() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
$.club_settings();
})(jQuery);
JavaScript only hoists declarations, not initializations.
The reference above displays how variables are hoisted but it works for functions too.
$(function() {
var previous_page = "<?=$_SESSION["previous_page"]?>";
if (previous_page == "bar_settings")
club_settings();
function club_settings() {
$(".bar_settings").fadeIn(1000);
$(".bar_photos").hide();
$(".bar_activities").hide();
$(".bar_campaigns").hide();
$(".etkinlik_ekle").hide();
$(".kampanya_ekle").hide();
}
})(jQuery);
The drawback would be is that it would be found in your $ variable which may lead to codes elsewhere breaking. But that could be another question.
Trying to resolve this by doing $.club_settings() = function club_settings() { ... will not work unless you reorder your codes as suggested by Mike

Passing parameters to a event listener function in javascript

Hello I have some code in which I take user input through in html and assign it to,two global variables
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
Which next show up in this addeventlistener function as parameters of the whowon function
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
The click event is meant to trigger the whowon function and pass in the parameters
function whowon(FirstScore, SecondScore, FirstTeam, SecondTeam) {
if (FirstScore > SecondScore) {
FirstTeam.win();
SecondTeam.lose();
} else if (FirstScore < SecondScore) {
SecondTeam.win();
} else {
FirstTeam.draw();
SecondTeam.draw();
}
}
However the values are null,as I get a cannot read properties of null error on this line
var spursscoref = document.getElementById("spursscore").value;
I am pretty sure the problem is coming from the addlistener function,any help would be appreciated
Well you could do something like this -
$( document ).ready(function() {
var d = document.querySelector("#gut2");
d.addEventListener("click", function () {
var spursscoref = document.getElementById("spursscore").value;
var livscoref = document.getElementById("livscore").value;
whowon(spursscoref, livscoref, spurs, liverpool)
}, false);
});
Wrap your code in $(document).ready(function(){}). This will ensure that all of your DOM elements are loaded prior to executing your Javascript code.
Try putting all of your code inside this
document.addEventListener("DOMContentLoaded", function(event) {
//Your code here
});
My guess is that your code is executed before the html actually finished loading, causing it to return null.

Self-Invoking Function Scope with Dynamically Binded Content

I have wrapped my JavaScript in a self-invoking function to keep everything contained. Hoever, I have run into an issue where my links, which are dynamically built on the fly, return an error "Function not defined" when they are clicked. Let me include my relevant code:
(function(window, document, $) {
function buildChapterList() {
for(var i=0; i<Object.keys(theChapterCues).length; i++) {
chapterListHTML = "<li><a class='fun-blue' href='javascript:void(0)' onClick=\"skipToChapter('"+ i +"')\">"+ theChapterCues[i]["title"] +"</a></li>";
$(chapterListHTML).appendTo("ul#chapter-list");
$("body").bind("DOMNodeInserted", function() {
$(this).find('#chapter-list li').first().addClass("active");
});
}
}
function skipToChapter(theChapter) {
if (theChapter == 0) {
theVideo.currentTime=0;
} else {
var thisChapterStart = parseInt(cues[theChapter]["chapterStart"]+1);
theVideo.currentTime=thisChapterStart/frameRate;
}
}
}(this, this.document, this.jQuery));
When clicking on one of the generated links I receive the following error:
Uncaught ReferenceError: skipToChapter is not defined
Am I missing something on scope? Is this a binding issue? Any advice would be greatly appreciated. Thanks!
The skipToChapter function is not in the global scope, so can't be called from an inline click handler. Instead you should assign the click handler when you build the link, in an unobtrusive way like below. If you assign it like this, then skipToChapter is in scope, and you don't have to make it a global, and you remove the need for undesirable inline event handlers.
function buildChapterList() {
for(var i=0; i<Object.keys(theChapterCues).length; i++) {
chapterListHTML = $("<li><a class='fun-blue' href='javascript:void(0)'>"+ theChapterCues[i]["title"] +"</a></li>");
(function(i){
chapterListHTML.find('a').click(skipToChapter.bind(this, i));
})(i);
chapterListHTML.appendTo("ul#chapter-list");
$("body").bind("DOMNodeInserted", function() {
$(this).find('#chapter-list li').first().addClass("active");
});
}
}
skipToChapter function is only visible within the outer anonymous function. You can read about Javascript scope here: http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/
The quick and dirty way of solving the problem would be defining skipToChapter outside of the anonymous function or as a member of the window object.
For example:
window.skipToChapter = function(theChapter) {
if (theChapter == 0) {
theVideo.currentTime=0;
} else {
var thisChapterStart = parseInt(cues[theChapter]["chapterStart"]+1);
theVideo.currentTime=thisChapterStart/frameRate;
}
}
However, be aware that this is not the best practice for binding a function to an event as it makes skipToChapter global and uses inline event handlers (http://robertnyman.com/2008/11/20/why-inline-css-and-javascript-code-is-such-a-bad-thing/).
A better approach would be:
function buildChapterList() {
for(var i=0; i<Object.keys(theChapterCues).length; i++) {
chapterListHTML = "<li><a class='fun-blue' href='javascript:void(0)' data-index='" + i + "'>"+ theChapterCues[i]["title"] +"</a></li>";
var $chapterListHTML = $(chapterListHTML);
$chapterListHTML.appendTo("ul#chapter-list");
$chapterListHTML.find('a').click(skipToChapter);
$("body").bind("DOMNodeInserted", function() {
$(this).find('#chapter-list li').first().addClass("active");
});
}
}
function skipToChapter() {
var theChapter = $(this).data('index');
if (theChapter == 0) {
theVideo.currentTime=0;
} else {
var thisChapterStart = parseInt(cues[theChapter]["chapterStart"]+1);
theVideo.currentTime=thisChapterStart/frameRate;
}
}
Read this answer for more information on event binding on dinamically created elements, with jQuery: Event binding on dynamically created elements?

element id is not accessible javascript

i have the following code. here i am declaring all the element id's to variables as global before all the functions declared. but those variables are taken by the functions
below is the sample:
var ddlpf=document.getElementById('<%=ddlpf.ClientID%>');
var disp_msg=document.getElementById('<%=disp_msg.ClientID%>');
function btn_proceed_Click()
{
var ses='<%=Session("hcur").toString %>';
if(pos_valid()==true)
alert('success');
}
function pos_valid()
{
var pos_valid=false;
var ses;
var ccy;
var ccy1;
var ccy2;
var as11costbud;
ses='<%=Session("hcur").toString %>';
var bm='<%=Session("benchmark").toString %>';
var dtsheet='<%=Session("dtsheet").toString %>';
var ratedis='<%=Session("ratedis").toString %>';
if(ddlpf.selectedIndex <= 0)
{
message("Please select the Portfolio");
return;
}
pos_valid=true;
return pos_valid;
}
function message(msg)
{
disp_msg.innerHTML=msg;
var modalPopupBehaviorCtrl = $find('modalpop');
modalPopupBehaviorCtrl.set_PopupControlID("poppan");
modalPopupBehaviorCtrl.show();
}
If i declare the variable "ddlpf" inside the pos_valid() and "disp_masg" inside the message(), it works.
the code is like this:
function pos_valid()
{
var ddlpf=document.getElementById('<%=ddlpf.ClientID%>');
//code
}
function message()
{
var disp_msg=document.getElementById('<%=disp_msg.ClientID%>');
//code
}
but these id's are common to 5 functions. not only this two. i have 20 id's which are common to 5 big functions. thats why i have declared them outside the functions.
what change should i make?
I am guessing you are putting the script at the top of the HTML page. So the page has not finished loading yet and you are trying to access the document.getElementById even before the document.body is ready. So when you access them in your functions, the variables value will be undefined => your problem
Try it this way,
var ddlpf;
var disp_msg;
window.onload = function(){
ddlpf=document.getElementById('<%=ddlpf.ClientID%>');
disp_msg=document.getElementById('<%=disp_msg.ClientID%>');
}
This way, you can put the code anywhere.
As far as i understood your question and with the code provided you are wondering
why your global variables appear not to work ddlpf and disp_msg is not working inside pos_valid and message functions
You have to make sure that the global variables are declared before any function is using them. Another option would be to pass in the variables.
In my demo on codepen you can see that it works. This html
<h2>Element id is not accessible</h2>
<select id="ddlpf">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<button onclick=btn_proceed_Click()>proceed</button>
<div id="disp_msg">
</div>
and this javascript
var ddlpf=document.getElementById('ddlpf');
var disp_msg=document.getElementById('disp_msg');
function btn_proceed_Click()
{
if(pos_valid()==true)
{
var btn = document.getElementById('btn');
btn.innerHTML='success';
};
}
function pos_valid()
{
var pos_valid=false;
var ses, ccy, ccy1, ccy2, as11costbud;
var selectedIndex = ddlpf.selectedIndex
if(selectedIndex <= 0)
{
message("Please select the Portfolio. Your selection:" + selectedIndex);
return;
}
message("Your selection" + selectedIndex);
pos_valid=true;
return pos_valid;
}
function message(msg)
{
disp_msg.innerHTML=msg;
}
If you provide more information erromessages from chrome dev tools we can help better.

Categories

Resources