onclick method add both bind and parameter - javascript

I have 2 methods. displayBookmark and deleteBookmarks. Currently I have onclick event that executes my deleteBookmark() method and also executes this.displayBookmark(). Without binding "this" element i couldn't execute this.displayBookmark(). My question how to get url parameter to deleteBookmark method?
I can't make it work on codepen so I will include github link
${onclick = this.deleteBookmark.bind(this)}
displayBookmark(){
this.bookmarksResults.innerHTML = ``;
for (let index = 0; index < bookmarks.length; index++) {
let name = (bookmarks[index].siteName).charAt(0).toUpperCase() + bookmarks[index].siteName.slice(1);
let url = bookmarks[index].siteUrl;
elements.bookmarksResults.innerHTML +=
`
<ul>
<li><h2 ><a class = "bookmarkResults__title" href="${url}" target = "_blank">${name}</a></h2>
<a ${onclick = this.deleteBookmark.bind(this)} class = "button button__delete">Delete</a>
<a class = "button button__edit">Edit</a>
<a class = "button button__visit" href="${url}" target = "_blank">Visit</a>
</li>
</ul>
`
}
}
deleteBookmark(){
console.log(url);
this.displayBookmark();
}

Somebody already gave me a good solution but it didn't worked for me and as a result a guy deleted his comment. But he was right. Basically I needed to modify these lines.
${onclick = this.deleteBookmark.bind(this, url)}
deleteBookmark(url){
console.log(url);
this.displayBookmark();
}
The problem was that I saved empty url to local storage, and because of it I saw console.log(url) empty and I thought that it didn't worked. Turns out I needed to clean my local storage. Glad I solved it in the end.

Related

Put JavaScript value inside HTML

How to put JavaScript value inside HTML ?
I am trying to put JavaScript value inside HTML like below.
<p>
Check your Credit Score Here
</p>
To achieve the results, you can make use of document.getElementById('').href property:
HTML (added the id attribute to the <a> tag):
<p>
Check your Credit Score <a id="link" href="" target="_blank">Here</a>
</p>
JavaScript:
window.onload = function() {
var first_name = 'Peter';
document.getElementById('link').href = 'http://someaddress.com?first_name='+ first_name;
// debug your results
console.log(document.getElementById('link').href);
}
Here is the JSFiddle
do this if you want to change the link
document.querySelector('a').href = "http://someaddress.com?first_name=" + first_name;
You can do like this
<p>
Check your Credit Score
<a href="http://someaddress.com?first_name='+ first_name +'" target="_blank"
>Here</a >
</p>
<script type="text/javascript">
const a = document.querySelector('a');
const first_name = 'John';
a.href = 'http://someaddress.com?first_name=' + first_name ;
</script>
For best practice do an if check otherwise your selector might not be found in the dom.
Also, if in querySelector("...anything...") not querySelector("a") is given the editor won't suggest the href prop that exists or not. Hence, setAttribute makes more sense.
const URL = "http://someaddress.com?first_name="
const name = 'adiat'
const anchor = document.querySelector(".what-ever")
if(anchor){
anchor.setAttribute("href", `${URL}${name}`);
}else{
console.warn("element not found to replace href attribute")
}
// shorthand -> anchor?.setAttribute("href", `${URL}${name}`);
A robust way would be to use a token to replace, I've used {{FirstName}}. Use an attribute selector to select via that token then replace that token on the href attribute
let firstNameLinks = document.querySelectorAll("a[href*='{{FirstName}}'");
let firstName = "Bob";
for(i = 0; i < firstNameLinks.length; i++){
console.log(firstNameLinks[i].href)
firstNameLinks[i].href = firstNameLinks[i].href.replace("{{FirstName}}", firstName);
}
A link
Another link

text string output stops after first space, js/html

I apologize in advance, this is the first Stack Overflow question I've posted. I was tasked with creating a new ADA compliant website for my school district's technology helpdesk. I started with minimal knowledge of HTML and have been teaching myself through w3cschools. So here's my ordeal:
I need to create a page for all of our pdf and html guides. I'm trying to create a somewhat interactable menu that is very simple and will populate a link array from an onclick event, but the title="" text attribute drops everything after the first space and I've unsuccessfully tried using a replace() method since it's coming from an array and not static text.
I know I'm probably supposed to use an example, but my work day is coming to a close soon and I wanted to get this posted so I just copied a bit of my actual code.
So here's what's happening, in example 1 of var gmaildocAlt the tooltip will drop everything after Google, but will show the entire string properly with example 2. I was hoping to create a form input for the other helpdesk personnel to add links without knowing how to code, but was unable to resolve the issue of example 1 with a
var fix = gmaildocAlt.replace(/ /g, "&nb sp;")
//minus the space
//this also happens to break the entire function if I set it below the rest of the other variables
I'm sure there are a vast number of things I'm doing wrong, but I would really appreciate the smallest tip to make my tooltip display properly without requiring a replace method.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (i = 0; i < gmailvidTitle.length; i++) {
arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>
Building HTML manually with strings can cause issues like this. It's better to build them one step at a time, and let the framework handle quoting and special characters - if you're using jQuery, it could be:
var $link = jQuery("<a></a>")
.attr("href", gmaildocLink[i])
.attr("title", gmaildocAlt[i])
.html(gmaildocTitle[i]);
jQuery("#gmailList").append($link).append("<br>");
Without jQuery, something like:
var link = document.createElement("a");
link.setAttribute("href", gmaildocLink[i]);
link.setAttribute("title", gmaildocAlt[i]);
link.innerHTML = gmaildocTitle[i];
document.getElementById("gmailList").innerHTML += link.outerHTML + "<br>";
If it matters to your audience, setAttribute doesn't work in IE7, and you have to access the attributes as properties of the element: link.href = "something";.
If you add ' to either side of the variable strings then it will ensure that the whole value is read as a single string. Initially, it was assuming that the space was exiting the Title attribute.
Hope the below helps!
UPDATE: If you're worried about using apostrophes in the title strings, you can use " by escaping them using a . This forces JS to read it as a character and not as part of the code structure. See the example below.
Thanks for pointing this one out guys! Sloppy code on my part.
// GMAIL----------------------------
function gmailArray() {
var gmaildocLink = ['link1', 'link2'];
var gmaildocTitle = ["title1", "title2"];
var gmaildocAlt = ["Google's Cheat Sheet For Gmail", "Google 10-Minute Training For Gmail"];
var gmailvidLink = [];
var gmailvidTitle = [];
var gmailvidAlt = [];
if (document.getElementById("gmailList").innerHTML == "") {
for (i = 0; i < gmaildocTitle.length; i++) {
var arrayGmail = "" + gmaildocTitle[i] + "" + "<br>";
document.getElementById("gmailList").innerHTML += arrayGmail;
}
for (var i = 0; i < gmailvidTitle.length; i++) {
var arrayGmail1 = "";
document.getElementById("").innerHTML += arrayGmail1;
}
} else {
document.getElementById("gmailList").innerHTML = "";
}
}
<div class="fixed1">
<p id="gmail" onclick="gmailArray()" class="gl">Gmail</p>
<ul id="gmailList"></ul>
<p id="calendar" onclick="calendarArray()" class="gl">Calendar</p>
<ul id="calendarList"></ul>
</div>

Dynamically creating unique link or button for each result of a database query result

Basically, a list of results from a database query is inserted into a ul. I want the user to be able to click the result they are looking for and then have one of two things happen:
A unique link is created (such as a php GET request) using the ID of
the selected result
A JS function is called via the onClick
attribute, and the ID of the clicked result is sent as an argument.
The code below is what I have done so far - minus the functionality that I listed above.
The list as it is in the HTML:
<ul data-role="listview" id="treesUL" data-inset="true" style="visibility: hidden">
<li id="treesLI">
<div class="resultNames">
<span class="donorName">Donor</span>
for
<span class="honoreeName">Honoree</span>
</div>
<div class="resultInfo">
<span class="treeName">common</span>
on:
<span class="donationDate">Date</span>
</div>
<div class="resultDedication">
<span class="dedicationText">Dedication</span>
</div>
</li>
</ul>
The javascript that edits the list, based on the results of the query which is stored in the myTrees array. This function is called via a XMLHttpRequest object.
function showTreeContent()
{
if (requestObj.readyState == 4) //Request completed
{
//Retrieve the JSON encoded array, which is stored at index-key: media
var text = requestObj.responseText;
//alert(text);
var myTrees = jQuery.parseJSON(text).media;
$('#treesUL').text('');
//Alert the number of rows, for testing purposes
alert(myTrees.length + " results.");
//Loop through the JSON array, and add each element to a <li>, which is then added to the <ul>
for(var i = 0; i < myTrees.length; i++)
{
var tree = myTrees[i];
var li =$('#treesLI').clone();
li.removeAttr('id');
li.appendTo('#treesUL');
//li.find('.treeLink').setAttribute("href", "somelink url");
li.find('.donorName').text(tree['donor']);
li.find('.honoreeName').text(tree['honoree']);
li.find('.dedicationText').text("'" + tree['dedication'] + "'");
if (tree['common'] != '')
li.find('.treeName').text(tree['common']);
else
li.find('.treeName').text("Unknown Species");
li.find('.donationDate').text(tree['date']);
li.data('treeID','tree'+i);
}
}
}
I tried surrounding the contents of the li tag with an a tag, and then editing the href of the a tag, but I was unable to get that to work. I'm using jQuery Mobile for this project also. Let me know if you need any more information - any help is greatly appreciated!
First thing that I see strange is that you are calling $('#treesUL').text(''); that deletes the contents of the ul and than in the loop you request $('#treesLI') which was deleted above.
What i would do is create the HTML as a string and append it to the ul.
Example.
var html = '';
for(var i = 0, length = myTrees.length; i < length; ++i)
{
var tree = myTrees[i];
html += '<li class="treesLI" onClick="somefunction('+ tree.id+')">';
html += '<div class="resultNames"><span class="donorName">' + tree.donor + '</span>';
html += 'for <span class="honoreeName">'+ tree.honoree + '</span></div>';
html +='</li>';
$('#treesUL').append(html);
}
As you can see i added an onClick handler that calls a function that receives a parameter.
You can use that onClick function to make a GET request with $.axaj()
If you don't want to use onClick you can do:
$('#treesUL li').click(function(event){
});
Some other observations:
You can access the properties of an object using the . like this tree.dedication.
You should do your for like this for(var i = 0, length = myTrees.length; i < length; ++i)
it is 2 times faster in IE8

get file parameters in javascript call

I'm trying to create a script that will make it easier for users to use a custom button and I have something like
<script src="http://host.com/file.js?id=12345"></script>
What I wonder is how can I, in the file.js get that id parameter.
if I use document, it will get the original html page that has the script line and what I need is that id.
is there any way i can get that id successfully? What should be the scope?
added
the idea is that I can have several buttons in the page for example to have a small and simply list:
<ul>
<li><script src="http://host.com/file.js?id=12345"></script></li>
<li><script src="http://host.com/file.js?id=23456"></script></li>
<li><script src="http://host.com/file.js?id=34567"></script></li>
</ul>
this will ultimately translate to
<ul>
<li><a class="view40btn" href="#" data-id="12345"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="23456"><strong>V40</strong> Watch the video</a></li>
<li><a class="view40btn" href="#" data-id="34567"><strong>V40</strong> Watch the video</a></li>
</ul>
the list above will look like this in HTML:
My only issue is that I can't assign the correct id to the data-id attribute as this is generated in the file.js.
result
from Paulpro answer I got it working with his idea and knowing that the client will have much more scripts loaded and several with id's I changed it a bit for the final and working version:
var id = (function(){
var scripts = document.getElementsByTagName('script');
for(var i = 0, result = {}; i < scripts.length; i++)
if(scripts[i].hasAttribute('data-viewfileid'))
result['id'] = decodeURIComponent(scripts[i].getAttribute('data-viewfileid'));
return result['id'];
})();
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
the script for the user would only be:
<script data-viewfileid="4444" src="file.js" type="text/javascript"></script>
You can get the last script element on the page (which will always be the currently executing one):
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
Then modify one of the query string parsers from this question to work with that scripts src property:
var url = s.src;
var qs = url.substring(url.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][2]);
}
That will give you an object containing all the query string properties on the current script. You can just access the properties like:
result['id']; // '12345'
In summary
To get the id parameter from within file.js, add the following code to the top of file.js:
var id = (function(){
var scripts = document.getElementsByTagName('script');
var s = scripts[scripts.length - 1];
var qs = s.src.substring(s.src.indexOf('?') + 1).split('&');
for(var i = 0, result = {}; i < qs.length; i++){
qs[i] = qs[i].split('=');
result[qs[i][0]] = decodeURIComponent(qs[i][3]);
}
return result['id'];
})();
Make sure it is not in any callback functions like a DOMReady callback.
Edit: You can probably reduce your script to:
var scripts = document.getElementsByTagName('script');
var id = scripts[scripts.length - 1].getAttribute('data-viewfileid');
var html = '<a class="view40btn" href="#" data-id="' + id + '"><strong>V40</strong> Watch the video</a>';
document.write(html);
JavaScript doesn't know anything about the script tag that loaded it. However, there are a few workarounds.
If the file is being preprocessed on the server, you could make the server render the value in the response:
(function() {
var id = <%= params.id %>;
//other stuff here
}());
Or you could give the script tag an id, and make your code find it and pull out the URL.
HTML:
<script src="http://host.com/file.js?id=12345" id="myscript"></script>
JS:
var id = document.getElementById('myscript').split('id=')[1];
Or in modern browsers you could perhaps do something like this to find script tags that match where you know the script is.
var scriptTag = document.querySelector('script[src^="http://host.com/file.js"]');
var id = scriptTag.src.split('id=')[1];
One more solution is to parse .js files with php interpreter. For example in apache configuration:
AddType application/x-httpd-php .js
And in JS:
alert('<?=$_GET["id"]?>');
You can put an ID on anything, including a script tag. So you can do something like this:
HTML:
<script id="myScript" src="http://host.com/file.js?id=12345"></script>
JS:
document.getElementById('myScript').src.split('=')[1]; to get the ID from that particular example string.
If that query string represents a timestamp (in which case you need the latest version) you can modify the JavaScript code to fetch the latest <script> tag like so:
var scripts = document.getElementsByTag('script');
var latestScriptId = scripts[scripts.length-1].src.split('=')[1];
EDIT: In the context of your new edit, you would then take latestScriptId and assign it to the data.id attribute corresponding to the button you would like to create...though again, semantically, it would just make more sense to use HTML's given id attribute, and additionally, since you are not using the href property for the anchor <a> tag, you're better off using a <button> element. So something like this would suffice:
var myButton = document.createElement('button');
myButton.className += 'view40btn';
myButton.id = latestScriptId;
According to your clarifications, what you asking how to do is not what you want to do.
Instead, include one script, and have multiple placeholder nodes.
HTML:
<ul>
<li class="mybutton" data-id="12345"></li>
<li class="mybutton" data-id="23456"></li>
<li class="mybutton" data-id="34567"></li>
</ul>
<script src="myscript.js"></script>
JS:
// myscript.js
var buttons = document.getElementsByClassName('mybutton');
for (var i = 0; i < buttons.length; i++) {
var button = buttons[i];
button.innerHTML = "my button html template here with id: "+ button.dataset.id;
}
See it work here: http://jsfiddle.net/zAdnB/
Javascript code does not "realise", that it is a part of some file. JS file is not "executable", there is no main method, which should be run after loading the file. You can not pass GET parameters to it - it is not clear how they should be interpreted.
In your HTML page, you should listen to "onload" method and then call the function from your file with your parameter.

Changing HTML with javascript

I'm trying to replace every instance of "Administrator" on my page with "Admin" Or something similar to that. How would I replace that? If it helps, the span is inside an tag that has the class "user-title".
Like this page but I kinda need to be fed the answer. This is my first time working with javascript.
<ul class="author-ident">
<li class="username">
<a title="Go to Different55's profile" href="http://fwin.co.cc/pun/profile.php?id=2">Different55</a>
</li>
<li class="usertitle">
<span>Administrator</span>
</li>
<li class="userstatus">
<span>Online</span>
</li>
</ul>
I work mostly with JQuery so I can only give you a JQuery solution of the top of my head. Sorry if this is not an option for you. With JQuery you could do this...
$(".user-title").each(function(index){
$(this).html($(this).html().replace("Administrator", "Admin"));
});
NOTE: If you expect more than one instance of "Administrator" per span tag then you will need to do a regex replace like follows...
.replace(/Administrator/g, "Admin");
See this for more info on the regex flag (e.g. "g" means global - more than one)
EDIT: Here is a javascript version....
var spans = document.getElementsByClassName("user-title");
for (var i = 0; i < spans.length; i++)
{
spans[i].innerHTML = spans[i].innerHTML.replace(/Administrator/g, "Admin");
}
ANSWER: This is based on your provided sample HTML (note that I have changed the class name "usertitle" based on your html, check if this is correct)...
var parents = document.getElementsByClassName("usertitle");
for (var i = 0; i < parents.length; i++)
{
var spans = parents[i].getElementsByTagName("span");
for(var j = 0; j < spans.length; j++){
spans[j].innerHTML = spans[j].innerHTML.replace(/Administrator/g, "Admin");
}
}
The JQuery equivalent...
$(".usertitle span").each(function(index){
$(this).html($(this).html().replace("Administrator", "Admin"));
});
<script type="text/javascript">
function changeText(){
document.getElementById('anId').innerHTML = 'my friend';
}
</script>
<p>Welcome to the site <b id='anId'>dude</b> </p>
<input type='button' onclick='changeText()' value='Change Text'/>
This will change the content of that .
You can run JS that will look in every span and, if you find "administrator", that you can be use that snippet of code.
To do the replacement you mentioned (replacing all occurrences of Administrator with Admin inside all spans inside .user-title, use:
$('.user-title span').each(function() {
$(this).html($(this).html().replace(/Administrator/g, 'Admin'));
});
NOTE: Assuming you are using jQuery in your app
You can use this function :
function correct() {
var a = document.getElementsByClassName("user-title");
var i = 0;
for(i=0; i<a.length; i++) {
while((a[i].innerHTML).indexOf("Administrator") >= 0){
a[i].innerHTML = a[i].innerHTML.replace(/Administrator/g, 'Admin');
}
}
}
this function will get collection of all elements having class name as "user-title". then the n in for loop, we will access each element in collection, see if it's innerHTML has the word that you want to replace and if it has, we replace it.
Put all instances of the word "Administrator" into a <span> with a certain class, f.i.:
<span class="user_type">Administrator</span>
Then you can use jQuery to do:
$("span.user_type").html("Admin");
Note that this may not be the nicest thing to do but we don't have any other details on what you're trying to accomplish.

Categories