Javascript/JQUERY local variable - javascript

I have 2 pieces of code
Javascript:
function changeImage(event){
event = event || window.event;
var targetElement = event.target || event.srcElement;
if (targetElement.tagName == "IMG") {
npath = document.getElementById("main_img").src = targetElement.getAttribute("src");
}
}
and JQUERY
var bpath = npath.replace("_n", "_b");
$(document).ready(function(){
$('div.prod_seeds_mimg_div').zoom({url: bpath});
});
I want to access npath variable from Javascript block, change it and use in JQUERY. But npath variable is not defined outside of Javascript. I've tried to make it global by skipping var and declare npath on top of two blocks (var npath = "";) but these methods are not helped.
Is there some way to access npath from JS and use it further?
Thanks.

EDITED
Try to use the following code:
$(document).ready(function(){
$('.prod_seeds_mimg_div').zoom({url: $('#main_img').attr('src')});
$('div.prod_seeds_oimg_div img').on('click', function(){
changeImage($(this).attr('src'));
});
});
function changeImage(imagePath){
$('#main_img').attr('src', imagePath);
$('.prod_seeds_mimg_div').zoom({url: imagePath});
}
And remember to remove the changeImage onClick trigger from your HTML source.

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

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.

Javascript - Uncaught ReferenceError - Code seems perfect?

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#');
});

Keeping variables between function executions (Javascript)

I have a JavaScript function that runs every time one of the many links is clicked. The functions first checks what the id of the link clicked is, then it runs an if stement. depending on the id of the link, different variables are defined.
All this works, but the problem is that some links define one variable while other links define another, I need to keep the variables defined in previous executions of the function defined for other executions of the function.
An example follows:
$(document).ready(function()
{
$(".sidebar a").click(function(event) {
event.preventDefault()
var targetID = $(this).attr("data-target")
$("#" + targetID).attr("src", $(this).attr("href"))
var element = $(this).attr("class")
if (element == "submit") {
var submit = $(this).attr("user")
alert("1")
} else if (element == "view") {
var view = $(this).attr("user")
alert("2")
}
})
window.history.replaceState({}, 'logs', '/file/path?submit=' + submit + '&' + 'view=' + view)
})
Thanks
You can use an outer function which does nothing but declare some variables and return an inner function. The inner function can access the variables from the outer scope which stay the same for every call of the function.
Example
var next = (function() {
var value = 0;
function next() {
return value++;
}
}());
console.log(next());
console.log(next());
console.log(next());
Live demo
http://jsfiddle.net/bikeshedder/UZKtE/
Define the variables in an outer scope:
$(document).ready(function () {
var submit;
var view;
$(".sidebar a").click(function (event) {
event.preventDefault();
var targetID = $(this).attr("data-target");
$("#" + targetID).attr("src", $(this).attr("href"));
var element = $(this).attr("class")
if (element == 'submit') {
submit = $(this).attr("user")
alert("1")
} else if (element == 'view') {
view = $(this).attr("user")
alert("2")
}
});
});
Create var submit and view outside of the function so it has a global scope.
You can store arbitrary data on a matched element with JQuery's .data() function.
Example:
$(this).data("submit", $(this).attr("user")); // set a value
var submit = $(this).data("submit"); // retrieve a value
This places the data in the context of JQuery's knowledge of the element, so it can be shared between function calls and even between different events.

Categories

Resources