What is wrong with this js function? - javascript

Here is a part of my script:
function create(panel_id,iframe_source,handle_title) {
var temp1=document.createElement("a");
temp1.setAttribute("href","#");
var attr=document.createAttribute("onClick");
attr.nodeValue="showPanel(panel_id)";
temp1.setAttributeNode(attr);
temp1.className="controller";
temp1.innerHTML=handle_title;
div.appendChild(temp1);
}
function showPanel(panel_id) {
var elem = document.getElementById(panel_id);
elem.classList.toggle("show");
}
And here is the part where I call the first function:
create
When I call it, every element is created correctly and working except for the onClick attribute.I noticed that when I change the function like this:
...
attr.nodeValue="showPanel('test')";
...
everything is working fine..Can someone tell me what I have done wrong plz?

Change:
attr.nodeValue="showPanel(panel_id)";
to:
attr.nodeValue="showPanel('" + panel_id + "')";

there are two problems
1) onClick should be onclick
2) "showPanel(panel_id)"; should be
"showPanel('" + panel_id + "')";
try this
function create(panel_id,iframe_source,handle_title) {
var temp1=document.createElement("a");
temp1.setAttribute("href","#");
var attr=document.createAttribute("onclick");
attr.nodeValue="showPanel('" + panel_id + "')";
temp1.setAttributeNode(attr);
temp1.className="controller";
temp1.innerHTML=handle_title;
div.appendChild(temp1);
}
function showPanel(panel_id) {
var elem = document.getElementById(panel_id);
elem.classList.toggle("show");
}

Related

Overriding angularJS directive functioning

I am using angular-pageslide directive in my project.
I am facing a problem that when I click anywhere on the body of the pageslide, when the slider is open, a class that I have added to HTML changes to 'close' one instead of staying 'open' one.
(Basically onClick changes ng-pageslide-body-open to ng-pageslide-body-closed).
This is happening because the angular pageslide directive calls a function to setClass, using onClick.
if (param.keyListener) {
$document.off('keydown', handleKeyDown);
}
if (param.clickOutside) {
$document.off('touchend click', onBodyClick);
}
isOpen = false;
setBodyClass('closed');
scope.psOpen = false;
function setBodyClass(value){
if (param.bodyClass) {
var bodyClass = param.className + '-body';
var bodyClassRe = new RegExp(bodyClass + '-closed|' + bodyClass + '-open');
body.className = body.className.replace(bodyClassRe, '');
var newBodyClassName = bodyClass + '-' + value;
if (body.className[body.className.length -1] !== ' ') {
body.className += ' ' + newBodyClassName;
} else {
body.className += newBodyClassName;
}
}
}
However, I need to stop that from happening using my own controller. Is there any way through which I can achieve that?
I tried using the Timeout function, which works but because it requires a millisecond parameter, it doesn't look correct.
Any suggestions?

How to run a function from a link created in javascript

I have a function in a javascript file that adds a link to a paragraph that I created in the HTML file. I want to call a function that is defined in the javascript file when the user clicks the link.
My HTML:
<p id="para"></p>
My JavaScript:
var paraHTML = document.getElementById("para");
function addLink(id) {
paraHTML.innerHTML += '<a id="' + id + '" onclick="clickedTest(); return false;">Click me!</a>'
}
function clickedTest() {
console.log('here');
}
I have also tried using href e.g.
paraHTML.innerHTML += '<a id="' + id + '" href="javascricpt:clickedTest();">Click me!</a>'
But both ways give me an error saying: ReferenceError: clickedTest is not defined
I have tried using the following code from this question but the number of links is constantly changing whilst my code is running which makes it difficult to use:
var elements = document.getElementsByTagName('a');
for(var i = 0, len = elements.length; i < len; i++) {
elements[i].onclick = function () {
console.log('here')
}
}
The addLink() function is called elsewhere in my javascript program several times
Using innerHTML to create content is usually slow and is usually discouraged, a more organic approach will be to create the element pragmatically and then adding event listener to that element. For example,
var elem = document.createElement('a');
elem.addEventListener('click', myClickHandler);
elem.innerText = 'My Tag';
paraHTML.appendChild(elem)
function myClickHandler(e) {
console.log('a is clicked')
}
This will not only fix your problem but will make your code more manageable
You can do something like this:
function callMe(){
}
var newLink = document.createElement('a');
newLink.href="javascript:callMe();";
newLink.innerHTML="this is a link";
paraHTML.appendChild(newLink);

Jquery Json not working properly

I have the following which works fine:
$('<li><a id=' + loc.locId + ' href="/DataEntry" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
$("#btnList a").click(function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
When I have the following, I can't even get to the click to display an alert message:
$.getJSON('/Home/GetLocType', { "locId": loc.locId }, function (result) {
var str = JSON.stringify(result);
if (str == '1') {
$('<li><a id=' + loc.locId + ' href="/DataEntry" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
} else {
$('<li><a id=' + loc.locId + ' href="/DataEntry/PotableForm" rel="external">' + loc.locName + '</a></li>').appendTo("#btnList");
}
$("#btnList").listview('refresh');
});
$("#btnList a").click(function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
Note sure what the difference is. I need to use Json as based on value, I need to go to a either of the 2 hyperlinks.
Use event delegation since anchor is created dynamically in your ajax call or bind the event (only for the added element) inside the ajax success callback. on syntax will work if your jquery version >= 1.7 for earlier versions take a look at live
$("#btnList").on('click', 'a', function () {
alert(siteName);
localStorage["dataEId"] = $(this).attr("id");
localStorage["dataESiteName"] = siteName;
localStorage["dataESysName"] = sysName;
localStorage["dataELocName"] = $(this).text();
}
Your first syntax works because it binds the click event to the anchor that exists underneath btnList, but it doesn't bind event to the ones added during the ajax calls in a later point in time.

Adding variable at the end of URL using jQuery

So far I have done
jQuery:
function addURL(element)
{
var baseZipCode = 48180;
$(element).attr('href', function() {
return this.href + baseZipCode;
});
}
html:
<a onclick="addURL(this)" href="http://www.weather.com/weather/today/" target="_blank">Click this</a>
My problem is when user clicks on link and the new window open everything is ok, but when the user clicks on the link again without a refresh, the variable is added twice to the link.
For example:
First time:
http://www.weather.com/weather/today/48180
Second time:
http://www.weather.com/weather/today/4818048180
It doesn't act right until you do a page refresh, any help would be appreciated. Thanks in advance
Replace your addURL function with
function addURL(element)
{
var baseZipCode = '48180';
if (element.href.slice(-baseZipCode.length) !== baseZipCode){
element.href += baseZipCode;
}
}
there is no jQuery involved..
You can try it with jQuery.fn.one
Javascript:
jQuery("a").one("click", function(){ // Set a handler that execute once
var baseZipCode = 48180;
this.href += baseZipCode; //same as "this.href = this.href + baseZipCode"
});
HTML:
Click this
Maybe you will need to add some class to <a> tags to differ it from another ones
This should be:
function addURL(element)
{
var baseZipCode = 48180;
element.href = (element.href + baseZipCode)
.replace(baseZipCode + baseZipCode, baseZipCode);
}
return this.href.indexOf(baseZipCode) != -1 ? this.href : this.href + baseZipCode;

Reload all images on page

I'm trying to get all the images in the page to reload including backgound-image: rules
I have some semi working code but I want to know if there is an easier way of doing this.
function cacheBuster(url) {
return url.replace(/\?cacheBuster=\d*/, "") + "?cacheBuster=" + new Date().getTime().toString();
}
$("img").each(function() {
this.src = cacheBuster(this.src);
});
$("*").each(function() {
var bg_img = $(this).css("background-image");
if (bg_img !== "none") {
var url = /url\((.*)\)/i.exec(bg_img);
if (url) {
$(this).css("background-image", "url(" + cacheBuster(url[1]) + ")");
}
}
});
Looks fine but you are missing inputs with type=image, that is images that act as a submit button. You can include them by adding following code
$("img, input[type=image]").each(function() {
this.src = cacheBuster(this.src);
});
Also you can change the code where you loop through all elements, just to include visible ones, if it is acceptable in your case.
$("*:visible")
Hope this helps.

Categories

Resources