Twitter Intent link is not opening in a new window - javascript

I have created an interface that allows people to Tweet at certain individuals from a webpage. To do so, I am utilizing Twitter's web intents. At first, the page had a textarea that contained a placeholder tweet that was passed through as a text parameter when a user clicked a Reply button, but the scope has changed so that the user should be able to enter text in the textarea, click the button, and see the Twitter popup with their updated tweet, because user testing showed that people were less likely to tweet at people if they weren't able to edit the content on the page.
The problem is that while this code does update the Twitter intent link, it seems to have broken some functionality of the Twitter intent link. Most notably, the links do not open up in a small popup like they normally do - instead, they replace the current page. Also, the "in_reply_to" functionality is intermittent - certain links that should contain tweets to reply to do not, while others do.
Anyone tried to do anything like this? And if so, any advice? I'm at a loss at this point.
The HTML (we're using Django, hence the template logic):
<div class="response">
{%if quote.tweet_id%}
<textarea id="twitter_response_text" class="has_tweet_id" maxlength="140">{{quote.twitter_handle}} {{quote.twitter_text_default}}</textarea>
<label for="twitter_response_text"><span></span></label>
<a class="hasReply" data-tweet-id="{{quote.tweet_id}}" href="https://twitter.com/intent/tweet?in_reply_to="><button value="respond" data-quote-id="{{quote.id}}"/><img src="{{STATIC_URL}}img/reply_arrow.png"> Reply</button></a>
{%else%}
<textarea id="twitter_response_text" maxlength="140">{{quote.twitter_text_default}}</textarea>
<label for="twitter_response_text"><span></span></label>
<button value="reply" data-quote-id="{{quote.id}}" /><img src="{{STATIC_URL}}img/reply_arrow.png"> Reply</button>
{%endif%}
</div>
Javascript:
$(".response a, .twitteraction a").on("click", function() {
//get text from the textarea of the current slide
var textarea = $(this).parents(".slide").find("#twitter_response_text")
if (textarea.val() !== "") {
text = textarea.val();
} else {
text = textarea.text();
}
//maybe we need the handle?
// var handle = $(this).parents(".slide").find("#twitterhandle").text();
//get the link
var link = $(this).attr("href");
//check to see if it needs reply link or regular
if ($(this).hasClass("hasReply")) {
//get the tweet id, stored as data attribute in the anchor
var tweetId = $(this).data("tweet-id");
//construct the query with a twitter id but no handle
var query = encodeURIComponent(tweetId) + "&text=" + encodeURIComponent(text) + "&related=ForecastFacts&original_referer=http://climatecliff.org/";
//add link to anchor
$(this).attr("href", (link + query));
} else {
//construct the query with text and related
var query = encodeURIComponent(text) + "&related=ForecastFacts&original_referer=http://climatecliff.org/";
//add query to anchor
$(this).attr("href", (link + query));
}
});

Turns out there is a way to remove the dependency on platform.twitter.com for their Javascript by adding it yourself - https://dev.twitter.com/docs/intents
Regarding the intermittent in_reply_to links, for some reason the data I attributes I had were adding 1 to the tweet_id that was being passed in the Django context. I'm not sure why, but I went ahead and refactored my code to only dynamically add the text, rather than the tweet id, since that isn't going to change.
Now it all works just fine.

Related

Is there a to change the value of an element using JavaScript

I'm trying to change the value of an element on a third-party web page using a JavaScript Add-on to display a hyperlink
I already have the link on the page i would like to be able to click it
I think I'm on the right track using document.getElementById although I'm not sure how to then change the id into a "a href" and then how to pass it back into the value.
Sorry, this is a bit of a tricky situation so I'll try my best to explain it. On a third-party web-page which we use for our HR related tasks, there is a section titled "File Link" although this isn't a link. When you copy and paste the address into a browser it displays the file. What i am trying to do is create a hyperlink on the "File Link" section to remove the need to copy and paste the link. Because this is a third party website. We have access to the JavaScript on the website and need to change the address into a hyperlink. I'm not entirely sure this is possible.The element id is "__C_cb_file_link" and i would like to insert the link address into the element using a variable then add the link parameters into the variable then reinsert it into the element/value.
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = "<a href="+intoLink+"</a>;
intoLink.value = hLink;
}
window.onload = linkIt();
<td><div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674"/></td></tr>
In below code first we read input value with new link (however we can read this value from other html tags), then we remove this element (and button) and add to parent element (of removed input) the new link
function linkIt() {
let intoLink = __C_cb_file_link.value;
let parent = __C_cb_file_link.parentNode;
__C_cb_file_link.remove();
btn.remove();
parent.innerHTML += `${intoLink}`;
}
<input id="__C_cb_file_link" value="https://example.com">
<button id="btn" onclick="linkIt()">Link It</button>
There are a number of issues with your code:
1) The code snippet in your question doesn't run because of a missing " at the end of the second line of the linkIt() function.
2) intoLink is a hidden field so anything you add to it will not be visible in the page
3) Even if point 2 were not true, setting the value of a form field will not cause HTML to appear on the page (at best you might get some plain text in a textbox).
4) "<a href="+intoLink+"</a>" doesn't work because intoLink is a complex object which represents the entire hidden field element (not just its value property). You can't convert a whole object into a string directly. You need to extract the value of the field.
A better way to do this is by creating a new element for the hyperlink and appending it to the page in a suitable place. Also I recommend not adding your event via onload - when written using this syntax only one onload event can exist in a page at once. Since you're amending another page which isn't under your control you don't want to disable any other load events which might be defined. Use addEventListener instead, which allows multiple handlers to be specified for the same event.
Demo:
function linkIt() {
var intoLink = document.getElementById("__C_cb_file_link");
var hLink = document.createElement("a");
hLink.setAttribute("href", intoLink.value);
hLink.innerHTML = "Click here";
intoLink.insertAdjacentElement('beforebegin', hLink);
}
window.addEventListener('load', linkIt);
<td>
<div class="sui-disabled" title="">m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674</div>
<input type="hidden" name="__C_cb_file_link" id="__C_cb_file_link" value="m-files://view/37FF751C-A23F-4233-BD8B-243834E67731/0-46524?object=C46A7624-D24B-45F3-A301-5117EFC1F674" /></td>
</tr>
P.S. m-files:// is not a standard protocol in most browsers, unless some kind of extension has been installed, so even when you turn it into a hyperlink it may not work for everyone.
[UPDATE] I supose that your "__C_cb_file_link" was a paragraph so I get the previous text http://mylink.com and create a link with, is it what you want, right?
function linkIt() {
let fileLink = document.getElementById("__C_cb_file_link");
let hLink = fileLink.textContent;
fileLink.innerHTML = ""+hLink+"";
}
linkIt();
<div>
<p id="__C_cb_file_link">http://myLink.com</p>
</div>

Make hyperlinks selectable

If you browse webpages using Firefox or Chrome, you can select text in a hyperlink, an element with <a> tag, by holding right alt key.
In my app, I want to achieve this using javascript, not by holding some button but by default. I will redirect to url if user doubleclicks, otherwise user will be able to select the content as if it's just a plain text.
First thing I tried is to replace all <a> elements with <span>elements and implement relevant events. This provides the functionality I wanted, but distorts the look considerably even tough I keep all attributes (class, id) same. It seems there are tag <a> specific css for the pages I'm dealing with.
Now what am trying is to achieve this by keeping tagname. My current code is as follows:
var linkElems = document.getElementsByTagName('a');
for (var i = linkElems.length - 1; i >= 0; i--) {
linkElems[i].ondblclick = function () {
//redirect to url
};
linkElems[i].setAttribute("href", "#");
linkElems[i].onclick = function () { return false; };
}
After this code, links does not make page redirect to respective url, but when I try to select the text it just drags some box having the url in it. To prevent that, I wrote this line of code:
document.body.ondragstart = function(){return false;}
Now, I prevent the drag but still can't select the text. I wonder is there a way to fix this.
See this.
I used data attribute and did not define href attribute.
You can find more information about data-* attribute on MDN
$(function(){
$(".aLink").dblclick(function(){
var link = $(this).attr("data-href");
window.location.href = link;
});
});
a {
color: blue;
text-decoration: underline;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a data-href="https://example.com" class ="aLink">Link 1</a> <br><br>
<a data-href="https://example.com/something" class ="aLink">Likn 2</a>

How to add HTML code to a different HTML file using JavaScript or PHP

Alrighty, so I am trying to make a little page on my website that takes a few values and then when you click a button, it adds those values inside of a div on a different HTML page.
My code is:
<input type="text" name="URL"><br>
<input type="text" name="ImageURL"><br>
<input type="text" name="Title">
<button onclick="addCode()">Submit</button>
So for the addCode() function I want it so that it adds the values inside of a the item div on a different HTML file just like:
<div class="item">
<div class="animate-box">
<a href=URL><img src=ImageURL></a>
<div class="fh5co-desc"><a style="TEXT-DECORATION:none; COLOR:#818892; LINE-HEIGHT:20px;" href=URL>Title</a></div>
</div>
</div>
Thanks in advance.
What you are doing is technically impossible. without some sort of persistence, that is;
you cannot edit a page you aren't on. web browsing is a stateless technology.
if you meant you want to fill out those inputs then redirect on click and have those values available, there are a few different ways to do it:
1) Query String
write your code on the second page in a way that it accepts params from a query string in the url bar
function getURLParameter(name) {
return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}
var textDecoration = getUrlParameter('textdec'),
color = getUrlParameter('color'),
lineHeight = getUrlParameter('lnheight');
then you can send the request for the page as
http://page.com/page?textdec="someval"&color="somecolor"&lnheight="someheight"
however this will not work if you are not going directly to that page after your current one
2) localStorage
on your first page set the local storage values:
localStorage.setItem('lineHeight', 'someVal');
localStorage.setItem('color', 'someColor');
localStorage.setItem('textDecoration', 'someVal');
then on your second page retrieve the values
var lineHeight = localStorage.getItem('lineHeight'),
color = localStorage.getItem('color'),
textDecoration = localStorage.getItem('textDecoration');
3) serverSide persistence
this will vary MASSIVELY depending on how you your backend is structured
but the general gist is make a post request (ajax or otherwise) &
collect the data on the backend
then when you render the second page send the variables that were posted, either through interpolation or included as script variables
The only way to do this (without getting other technologies involved) is to use the localStorage, storage event. And, even with this, it will only work when the two pages are coming from the same domain and are open in different browser tabs (of the same browser) at the same time.
If those conditions are present, then modifying localStorage on one page will fire the storage event, which the other page can be set up to listen for. The other page can then respond to the event by pulling new values (that the first page wrote into localStorage) out and placing them anywhere on the second page that you like.
This is the kind of solution that you might encounter if you were on a travel site with more than one browser tab open. You may be looking at different flight options in different tabs. If one tab's code has an update that any/all other open tabs should know about, this technique does the trick.
Here's an example of how to set values into localStorage and use them. But, localStorage doesn't work here in the Stack Overflow snippet environment, so you can run the code here.
Once the values are in localStorage, you can pick them up from any other page that is being served from the same domain. So, the "getItem" code I'm showing here would really be placed on your "page2.html".
// Get DOM references:
var name = document.getElementById("name");
var color = document.getElementById("color");
var airspeed = document.getElementById("airspeed");
var btn = document.getElementById("btnGo");
// Set up button click event handler:
btn.addEventListener("click", function(){
// Get values and place in localStorage
localStorage.setItem("name", name.value);
localStorage.setItem("color", color.value);
localStorage.setItem("airspeed", airspeed.value);
// For demonstration, get values out of localStorage
console.log("What is your name? ", localStorage.getItem("name"));
console.log("What is your favorite color? ", localStorage.getItem("color"));
console.log("What is the airspeed of a laiden swallow? ", localStorage.getItem("airspeed"));
// If you wanted to redirect the user to the second page, now that the intial values
// have been set, you could just do:
location.href = "path to second page";
});
<div>What is your name?<input type="text" id="name"></div>
<div>What is your favorite color?<input type="text" id="color"></div>
<div>What is the airspeed of a laiden swallow?<input type="text" id="airspeed"></div>
<button id="btnGo">Go!</button>
If you're trying to edit the actual source code of the file, you'll need something like PHP. Otherwise, JS is just fine.
PHP Solution
You could use something like this:
<?php
$old = file_get_contents("some_page.html");
$content = explode("<span>",$old,2); // replace <span> w/ opening tag
$content = explode("</span>",$content[1],2); // replace </span> w/ closing tag
$data = "new content of element";
$new = str_replace($content[0],$data,$old);
?>
Updated JS Solution
You can't use my previous solution. Instead, you would have to create a function in the second HTML file that could be called from the first file, like this:
A script in file2.html:
function set(id,val){
$("#"+id).html(val); // jQuery
document.getElementById(id).innerHTML = val; // pure JS
}
A script in file1.html:
var win = window.open("http://example.com"); // open the window
win.set("some_id","Some content.") // the function that we set earlier
Note that this is reverted once the user closes or reloads the tab, and only applies to that user and that tab.

How to read text from textfield using jQuery to the variable?

So, I got the page on my local server, and this page contains textarea and button. I am Trying to write onclick function to button, which would read whatever I typed in text area, and make record to database. Just like when I finish typing my question here, and press Ask Question. The problem is that I can't properly read text in text area, it basically sees only what was in there at the moment of loading a page, and just rewrite it. How should I get text, that I typed right before clicking the button? I just want to know how can I copy that text to some var, which I can PUT to database.
$.getJSON('/link/' + tenderId, function (data) {
var description = '';
description += '<textarea id="description" class="form-control" rows="3">' + data.description + '</textarea>';
$('#description').html(description);
});
Use this code inside your click event
var textareaValue = $('textarea#textareaId').val();
html
<textarea id="textareaId"></textarea>
SO answer: https://stackoverflow.com/a/144836/2772017
You need to use val() (I am guessing you are using text()) to get the text of a Text Area:
$('input#mybutton').click(function() {
var text = $('textarea#mytextarea').val();
});
Of course this is just guesswork as you did not supply any code! :)
Update:
The code you added is also incorrect as it adds a duplicate id of description inside a div with an id of description! ID's need to be unique on a page.
Assuming you want a new id here is a cleaner version of your code:
$.getJSON('/link/' + tenderId, function (data) {
var $textArea = $("<textarea>", {class: "form-control", id: "descriptionText", rows: "3"}).val(data.description);
$('#description').empty().append(description);
});
I can't figure out you method logic; it seems you are pulling some json data then appending it to a textarea while in issue description you said that you are trying to save the textarea content so you have to be sending it throug a POST request.
Also does the <textarea id="description"...> element is there in your page or you will be creating it at each button click?
If such is you case, you can try with the following snippet:
$.getJSON('/link/' + tenderId, function (data) {
var $description = $("<textarea>");
$description.attr({
id:'description',
class:'form-control',
rows:'3'})
.html(data.description);
//you will have then to append this jQuery element, e.g: $("#wrapper").append($description)
});
$('button').click(function(){
var myString = $('#description').val();
})
Then use myString whereever you like.

Programmatically turning on <strong></strong> for editable section in html5

I am working on an HTML5/javascript/php project where I have a which is set to be editable.
I know the user can be press ctrl + b to make the text bold, but I also want to allow the user to be able to click on the appropriate button on the web page to perform the same action.
I.e. when the user types it will be in normal text, they click on the bold button on the web page and it appends <strong> to the html of the section, and whatever they type now will be hold until they press the button again and it then appends </strong>.
However, at the moment when I append <strong> it seems to automatically add </strong> and I want to stop that from happening. Am I going about this the right way or is there a better way that this can be achieved.
Below is the javascript that I am trying to use
function enableDisableBold(section)
{
var boldEnabled = $("#boldEnabled").val();
var content = $("#" + section).html();
var newContent;
if (boldEnabled == "true")
{
$("#btnBold").removeClass("formatButtonsActivated");
$("#boldEnabled").val("false");
//newContent = content + "</strong>";
//$("#" + section).html(newContent);
}
else
{
$("#btnBold").addClass("formatButtonsActivated");
$("#boldEnabled").val("true");
newContent = content + "<strong>";
$("#" + section).html(newContent.replace("</strong>", ""));
}
alert($("#" + section).html());
}
Thanks for any help you can provide.
UPDATE
I've just come across another solution which does what I want to achieve, but there is a slight issue. At the end of the function call, I perform the following bit of code.
var article = document.getElementById(section);
article.focus();
document.execCommand("Bold", false, null);
The problem is this is working fine in Internet Explorer, but in Chrome is where I am having the problem. When I set the focus back to the <section> tag, it puts the cursor back to the beginning of the text. I read somewhere that putting onfocus="this.value = this.value;" on the control but this doesn't help.
I was trying to find a way of putting the cursor back to the end of the character, but I would actually need to put the cursor back to where it originally was. Is this something that can be done.
create a strong element and append your content to it
$('<strong />').append(content);

Categories