JavaScript Server element onclick event - javascript

Html
<a id="lnkShowExportBtn" runat="server">Look at image</a>
jQuery
lnkShowExportBtn.Attributes.Add("onclick", #"{ var rowImage = document.getElementById('rowImage');
if(rowImage.style.display == 'none')
{
rowImage.style.display = 'block';
var lnkShowExportBtn = document.getElementById('<%=lnkShowExportBtn.ClientID%>');
lnkShowExportBtn.innerHTML = 'Hide image';
}
else {
rowImage.style.display = 'none';
var lnkShowExportBtn = document.getElementById('<%=lnkShowExportBtn.ClientID%>');
lnkShowExportBtn.innerHTML = 'Look at image';
}
}");
Get this error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
What am I doing wrong? Just can't get to the point.
Thanks.

You are passing '<%=lnkShowExportBtn.ClientID%>' as a string and it is not evaluated to replace the real client id value, which you can see in the generated html. It would be a lot more simple if you add javascript in aspx and just bind it on server side.
In code behind
lnkShowExportBtn.Attributes.Add("onclick", "YourFunction()");
OR, in ASPX
<a id="lnkShowExportBtn" runat="server" onclick="YourFunction();">Look at image</a>
In javascript
function YourFunction()
{
var rowImage = document.getElementById('rowImage');
if (rowImage.style.display == 'none') {
rowImage.style.display = 'block';
var lnkShowExportBtn = document.getElementById('<%=lnkShowExportBtn.ClientID%>');
lnkShowExportBtn.innerHTML = 'Hide image';
} else {
rowImage.style.display = 'none';
var lnkShowExportBtn = document.getElementById('<%=lnkShowExportBtn.ClientID%>');
lnkShowExportBtn.innerHTML = 'Look at image';
}
}

Try this with jQuery : Here I have bind click event to lnkShowExportBtn and changing inner html of it with the help of if condition which checks of image visible. And by using .toggle(), I am making image hide and show.
$(document).ready(function(){
$('#lnkShowExportBtn').click(function(){
var innerHtml = 'Hide image';
if($('.rowImage').is(':visible'))
{
innerHtml = 'Look at image';
}
$(this).html(innerHtml);
$('.rowImage').toggle();
});
});
Demo
For more Information on jQuery : click jQuery

Related

Getting null value on the querySelector

I try to copy paste the code from Mozilla's getting started with Javascript tutorial
var myImage = document.querySelector('img');
myImage.onclick = function() {
var mySrc = myImage.getAttribute('src');
if(mySrc === 'images/firefox-icon.png') {
myImage.setAttribute ('src','images/firefox2.png');
} else {
myImage.setAttribute ('src','images/firefox-icon.png');
}
}
I am getting an error "Cannot set property 'onclick' of null". How can correct the code?
I am just getting started with javascript. please forgive me if it is a silly mistake from my part.
You might be trying to assign the click handler before the element has been rendered so the query selector will not find the img tag. Try executing your script after the page has rendered like so
window.onload = function () {
var myImage = document.querySelector('img');
myImage.onclick = function() {
var mySrc = myImage.getAttribute('src');
if(mySrc === 'images/firefox-icon.png') {
myImage.setAttribute ('src','images/firefox2.png');
} else {
myImage.setAttribute ('src','images/firefox-icon.png');
}
}
}

JQuery cookie set in other Function

I had a javascript Function showHide(shID) , which is a function to hide div or show content after clicked "read more" . Here is my Fiddle : http://jsfiddle.net/Garfrey/5xf72j4m/8/
As you see when user click on it and show more content , but I just need to hide once , means when the user come back to visit my page and the hidden content is still showing. So that I need to add JQuery cookie , but what I wrote was wrong and it's not working .I'am new in Javascript . Do anyone know how to fix it ? thanks in advance , I really need help .
here my code for function :
<script language="javascript" type="text/javascript">
jQuery(document).ready(function(){
if($.cookie("example")=='1') {
function showHide(shID) {
if (document.getElementById(shID+'-show').style.display != 'none') {
document.getElementById(shID+'-show').style.display = 'none';
document.getElementById(shID).style.display = 'block';
}
else {
document.getElementById(shID+'-show').style.display = 'inline';
document.getElementById(shID).style.display = 'none';
}
}
} else {
$.cookie("example", "1");
}
});
</script>
You can't define a function inside jQuery's ready function without doing something like this
var showHide;
$(function() { // Document ready
showHide = function(sh) {
//Insert function code here
};
});
I think in your case you might be better off defining the function outside of the ready function then binding it to the button's onclick handler dynamically.
I also added a data-showhide attribute to the button to pass the variable into the showhide function onclick.
function showHide() {
var shID = $(this).data("showhide"); // Use lower case only in data
if (document.getElementById(shID + '-show').style.display != 'none') {
document.getElementById(shID + '-show').style.display = 'none';
document.getElementById(shID).style.display = 'block';
} else {
document.getElementById(shID + '-show').style.display = 'inline';
document.getElementById(shID).style.display = 'none';
}
}
$(function() {
$("#example-show").on("click", showHide);
});
<a href="#" id="example-show" class="showLink" data-showhide="example">
The cookies can be set to specific values in the showHide function. The ready handler can then query the cookie and determine whether or not to show or hide the div.
This fiddle shows this in action http://jsfiddle.net/e52hxosb/19/

Stopping content script in chrome extension

I have developed chrome extension , I have added ,
chrome.browserAction.onClicked.addListener
which will start the script once clicked on , the script in turn will add a div at the bottom of the web page on the tab the browser action is clicked ,
All I have to do is , I need to add a close link which will stop the content script and close the div at the bottom ,
I have tried windows.close() , self.close() but nothing seems to work ,I would atleast want it to work in a way that 2nd time some one clicks on browser action, the script should stop.
Here is my code,
background.js
chrome.browserAction.onClicked.addListener( function() {
chrome.tabs.executeScript( { file: 'myscript.js' } );
});
myscript.js
document.body.appendChild(div);
document.addEventListener("click",
function (e) {
e.preventDefault();
var check = e.target.getAttribute("id");
var check_class = e.target.getAttribute("class");
if(check=="ospy_" || check=="ospy_id" || check=="ospy_text" || check=="ospy_el" || check=="ospy_class" || check=="ospy_name" || check=="ospy_href" || check=="ospy_src"|| check=="ospy_wrapper"|| check=="ospy_style"|| check=="ospy_rx"|| check=="ospy_con"|| check_class=="ospy_td"|| check=="ospy_main_tab"|| check_class=="ospy_tab" || check_class=="ospy_ip"|| check_class=="ospy_lab")
{
}
else{
document.getElementById('ospy_id').value = "";
document.getElementById('ospy_class').value = "";
document.getElementById('ospy_el').value = "";
document.getElementById('ospy_name').value = "";
document.getElementById('ospy_style').value = "";
document.getElementById('ospy_href').value = "";
document.getElementById('ospy_text').value = "";
document.getElementById('ospy_src').value = "";
document.getElementById('ospy_con').value = "";
document.getElementById('ospy_').value = "";
document.getElementById('ospy_rx').value = "";
var dom_id=e.target.getAttribute("id");
// var dom_id = e.target.id.toString();
var dom_name = e.target.name.toString();
var dom_class = e.target.className.toString();
// var dom_class = this.class;
var dom_html = e.target.innerHTML;
var dom_href = e.target.getAttribute("href");
var dom_text = e.target.text;
var dom_el= e.target.tagName;
var dom_src= e.target.src;
//var XPATH = e.target.innerHTML;
var rel_xpath = "";
var field ="";
var field_value = "";
field="id";
field_value = dom_id;
rel_xpath = dom_el+"[#"+field+"='"+field_value+"']";
if(dom_id == null){
field="href";
field_value= dom_href;
//var rel_xpath = dom_el+"[contains(text(), '"+dom_text+"')]";
rel_xpath = dom_el+"[#"+field+"='"+field_value+"']";
if(dom_href==null || dom_href=="#")
{
field="src";
field_value= dom_src;
rel_xpath = dom_el+"[#"+field+"='"+field_value+"']";
//rel_xpath = "nope nothing";
if(dom_src==null)
{
var rel_xpath = dom_el+"[contains(text(), '"+dom_text+"')]";
if(dom_text=="")
{
field="class";
field_value= dom_class;
rel_xpath = dom_el+"[#"+field+"='"+field_value+"']";
}
}
}
}
var con_xpath = "";
var con_xpath = dom_el+"[contains(text(), '"+dom_text+"')]";
if(dom_text==null)
{
con_xpath = "NA";
}
var css ="color: ";
css += getComputedStyle(e.target).color;
css +="\nWidth: ";
css += getComputedStyle(e.target).width;
css +="\nHeight: ";
css += getComputedStyle(e.target).height;
css +="\nbg: ";
css += getComputedStyle(e.target).background;
css +="\nfont: ";
css += getComputedStyle(e.target).font;
css +="\nvertical-align: ";
css += getComputedStyle(e.target).verticalalign;
css +="\nmargin: ";
css += getComputedStyle(e.target).margin;
var node = getXPath(e.target.parentNode);
document.getElementById('ospy_id').value = dom_id;
document.getElementById('ospy_class').value = dom_class;
document.getElementById('ospy_el').value = dom_el;
document.getElementById('ospy_name').value = dom_name;
document.getElementById('ospy_style').value = css;
document.getElementById('ospy_href').value = dom_href;
document.getElementById('ospy_text').value = dom_text;
document.getElementById('ospy_src').value = dom_src;
document.getElementById('ospy_').value = node;
document.getElementById('ospy_rx').value =rel_xpath;
document.getElementById('ospy_con').value =con_xpath;
}},
false);
window.close() is for closing a window, so no wonder it does not work.
"Unloading" a content-script is not possible, but if you want to remove an element (e.g. your div) from the DOM, just do:
elem.parentNode.removeChild(elem);
(Whether you bind this behaviour to a link/button in your <div> or have the browser-action, trigger an event in the background-page that sends a message to the corresponding content-script which in turn removes the element is up to you. (But clearly the former is much more straight-forward and efficient.)
If you, also, want your script to stop performing some other operation (e.g. handling click events) you could (among other things) set a flag variable to false (when removing the <div>) and then check that flag before proceeding with the operation (e.g. handling the event):
var enabled = true;
document.addEventListener('click', function (evt) {
if (!enabled) {
/* Do nothing */
return;
}
/* I am 'enabled' - I'll handle this one */
evt.preventDefault();
...
/* In order to "disable" the content-script: */
div.parentNode.removeChild(div);
enabled = false;
Notes:
If you plan on re-enabling the content-script upon browser-action button click, it is advisable to implement a little mechanism, where the background-page sends a message to the content-script asking it to re-enable itself. If the content-script is indeed injected but disabled, it should respond back (to confirm it got the message) and re-enable itself. If there is no response (meaning this is the first time the user clicks the button on this page, the background-page injects the content script.
If it is likely for the content script to be enabled-disabled multiple times in a web-pages life-cycle, it would be more efficient to "hide" the <div> instead of removing it (e.g.: div.style.display = 'none';).
If you only need to disable event handler, instead of using the enabled flag, it is probably more efficient to keep a reference to the listener you want to disable and call removeEventListener().
E.g.:
function clickListener(evt) {
evt.preventDefault();
...
}
document.addEventListener('click', clickListener);
/* In order to "disable" the content-script: */
div.parentNode.removeChild(div);
document.removeEventListener('click', clickListener);

Uncaught ReferenceError: X is not defined

This code is being used on a Chrome Extension.
When I call the "showOrHideYT()" function, I get a
"Uncaught ReferenceError: showOrHideYT is not defined | (anonymous
function) | onclick"
This code will search for youtube links in a page, and it will add a button (it's really a div with an event) next to the link to show the iframe with the embedded video, pretty much like Reddit Enhancement Suite. Consider the code, per se, incomplete. I just want to know what am i missing when i call the "showOrHideYT(frameZES12345)" function.
if needed, i can provide manifest.json.
Thanks
function showOrHideYT(id)
{
var YTvidWidth = 420;
var YTvidHeight = 315;
frameYT=getElementById(id);
console.log(frameYT.style.visibility);
if (frameYT.style.visibility == "hidden")
{
frameYT.style.width = YTvidWidth+"px";
frameYT.style.height = YTvidHeight+"px";
frameYT.style.visibility = "visible";
}
if (frameYT.style.visibility == "visible")
{
frameYT.style.width = "0px";
frameYT.style.height = "0px";
frameYT.style.visibility = "hidden";
}
};
// DOM utility functions
function insertAfter( referenceNode, newNode ) {
if ((typeof(referenceNode) == 'undefined') || (referenceNode == null)) {
console.log(arguments.callee.caller);
} else if ((typeof(referenceNode.parentNode) != 'undefined') && (typeof(referenceNode.nextSibling) != 'undefined')) {
if (referenceNode.parentNode == null) {
console.log(arguments.callee.caller);
} else {
referenceNode.parentNode.insertBefore( newNode, referenceNode.nextSibling );
}
}
};
function createElementWithID(elementType, id, classname) {
obj = document.createElement(elementType);
if (id != null) {
obj.setAttribute('id', id);
}
if ((typeof(classname) != 'undefined') && (classname != '')) {
obj.setAttribute('class', classname);
}
return obj;
};
///////////////////////////////////////
$(document).ready(function() {
var vidWidth = 420;
var vidHeight = 315;
var linksSemID = document.getElementsByTagName("a") ;
for (var i = 0; i < linksSemID.length; i++){
if (/id=$/.test(linksSemID[i].href)) links[i].href += "1";
}
i=0;
var youTubeRegExp = /(?:v=)([\w\-]+)/g;
var forEach = Array.prototype.forEach;
var linkArray = document.getElementsByTagName('a');
forEach.call(linkArray, function(link){
linkArray.id="zes" + i++;
var linkTarget = link.getAttribute('href');
if (linkTarget!=null)
{
if (linkTarget.search(youTubeRegExp) !=-1)
{
console.log (linkTarget);
idVideo=linkTarget.match(/(?:v=)([\w\-]+)/g);
//idVideo = idVideo.replace("v=", "");
//add buton
botaoMais = document.createElement('DIV');
botaoMais.setAttribute('class','expando-button collapsed video');
botaoMais.setAttribute('onclick','showOrHideYT(frameZES'+ i +')');
insertAfter(link, botaoMais);
//add iframe
ifrm = document.createElement('IFRAME');
ifrm.setAttribute('src', 'http://www.youtube.com/embed/'+ idVideo);
ifrm.style.width = '0px';
ifrm.style.height = '0px';
ifrm.style.frameborder='0px';
ifrm.style.visibility = 'hidden';
ifrm.setAttribute('id', 'frameZES' + i);
insertAfter(link, ifrm);
}
}
});
});
When you use setAttribute with a string, the event will be executed in the context of the page. The functions which are defined in a Content script are executed in a sandboxed scope. So, you have to pass a function reference, instead of a string:
Replace:
botaoMais.setAttribute('onclick','showOrHideYT(frameZES'+ i +')');
With:
botaoMais.addEventListener('click', (function(i) {
return function() {
showOrHideYT("frameZES"+ i);
};
})(i));
Explanation of code:
(function(i) { ..})(i) is used to preserve the value of i for each event.
Inside this self-invoking function, another function is returned, used as an event listener to click.
I see that you are using jQuery in your code. I personally think if we are using a library like jQuery, then we should not mix the native javascript code and jQuery code.
You can use jQuery bind to bind your the functions you need to call on dom ready.
Read below to know more.
suppose you want to call a javascript function on a button click, Here is the HTML for the same.
<div id="clickme">
<input id= "clickmebutton" type="button" value = "clickme" />
</div>
suppose "test" is the function you need to call, here is the code for test function.
function test() {
alert("hello");
}
you now need to bind the test function on the button click.
$(document).ready(function() {
$("#clickmebutton").bind("click", function(){
// do what ever you want to do here
test();
});
});

Use Javascript to make Image visible when page opens

I'm looking for Javascript that will fire when page opens and sets Image1 visibility to true.
Thanks
If you are referencing the CSS visibility property:
window.onload = function() {
document.getElementById( 'Image1' ).style.visibility = "visible";`
};
or the display property:
window.onload = function() {
document.getElementById( 'Image1' ).style.display = "block";
};
If you want it to occur right away utilize the document.onload method. I.e.
document.onload = loadFunc;
function loadFunc() {
document.getElementById( 'Image1' ).style.display = "block";
}
<script>
window.onload = function() {
document.getElementById("Image1").visibility = "visible";
}
</script>

Categories