I'm totally new to programming Twitter, so please excuse my ignorance. I've tried to find a solution to this problem, but to no avail..
In HTML I've got this:
<a href='javascript: submit_with_twitter()'>submit</a>
I'm using my own button to trigger the tweet because the button is actually a 'submit and tweet' button, not just a standard 'tweet' button.
in JS:
function submit_with_twitter() {
twttr.events.bind('click', function (event) {
alert("foo");
});
var myURL = encodeURIComponent("http://www.xxx.org.uk/compose-letter");
var my_text = encodeURIComponent("blah blah");
var url = "https://twitter.com/intent/tweet?url=" + myURL + "&text=" + my_text + "&via=xxx";
window.open(url, "Twitter", "status = 1, left = 430, top = 270, height = 550, width = 420, resizable = 0");
}
The twitter pop up window opens and the tweet can be posted successfully. But, 2 problems:
1) the tweet is actually the first stage of the form submit process, so when the tweet has been made JS needs to detect this so it can trigger the form submission
2) the pop up window does not close automatically
If I manually include the twitter JS like so:
<script type="text/javascript" src="//platform.twitter.com/widgets.js"></script>
I get this console error when my JS function is called:
Uncaught TypeError: Object function a(e){if(!e)return;var t,r,i,o;n.apply(this,[e]),t=this.params(),r=t.size||this.dataAttr("size"),i=t.showScreenName||this.dataAttr("show-screen-name"),o=t.count||this.dataAttr("count"),this.classAttr.push("twitter...<omitted>...t'
If I don't manually include the twitter JS, the tweet still works but there's no error message and nothing else happens.
I should add that all this is being done in wordpress. I include my own JS file in the WP page editor, as this seems to work best generally, and I have added:
<meta name="twitter:widgets:csp" content="on">
to the page.
------------ EDIT ---------------------
now I've got my JS like this:
jQuery(document).ready(function($) {
// Code here will be executed on document ready. Use $ as normal.
console.log("jQuery(document).ready");
$.getScript('https://platform.twitter.com/widgets.js', function(){
// console.log("twttr: "+twttr);
console.log("twttr object: %o", twttr);
console.log("jQuery object: %o", jQuery);
$(twttr).ready(function (twttr) {
console.log("twttr ready, adding tweet handler");
$(twttr.events).bind('tweet', function () {
console.log("tweeted event!");
});
$(twttr.events).bind('click', function () {
console.log("click event!");
});
$(twttr.events).bind('follow', function () {
console.log("follow event!");
});
});
});
});
which gets rid of all errors, the tweet window now closes itself and all the console logs are seen as expected, except for those which should appear after the tweet is made.
Basically, everything seems fine except that the tweet event is never caught!
Ok,
For future sufferers, I finally figured out that twitter was being set up elsewhere in wordpress, so there was no need to use
$.getScript('https://platform.twitter.com/widgets.js', function(){}
or
<script type="text/javascript" src="https://platform.twitter.com/widgets.js"></script>
or any other attempt to set up twitter widgets.
I haven't looked into which plugin (if any) is causing twitter to be initialised..
Also, if the page does not contain an HTML twitter link, something like this:
<a href='https://twitter.com/intent/tweet' >Tweet Test</a>
twitter is not initialised, so events cannot be detected. So, it's easiest to trigger the tweet normally using the link, then use the captured tweet event to run any subsequent JS, rather than using JS to trigger the tweet
Related
There have already been answers to this question but I am still unsure exactly how it works.
I am using the following HTML in my footer.php:
<div id="popup">
<div>
<div id="popup-close">X</div>
<h2>Content Goes Here</h2>
</div>
</div>
and the following Javascript:
$j(document).ready(function() {
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
});
Everything works great, but I want to only show the pop up once per user (maybe using the cookie thing all the forum posts go on about) but I do not know exactly how to incorporate it into the JS above.
I know that I will have to load the cookie JS in my footer with this:
<script type="text/javascript" src="scripts/jquery.cookies.2.2.0.min.js"></script>
But that is all I understand, can anyone tell me exactly how the JS/jQuery should look with the cookie stuff added?
Thanks
James
*Note : This will show popup once per browser as the data is stored in browser memory.
Try HTML localStorage.
Methods :
localStorage.getItem('key');
localStorage.setItem('key','value');
$j(document).ready(function() {
if(localStorage.getItem('popState') != 'shown'){
$j('#popup').delay(2000).fadeIn();
localStorage.setItem('popState','shown')
}
$j('#popup-close, #popup').click(function() // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hidden.
});
});
Working Demo
This example uses jquery-cookie
Check if the cookie exists and has not expired - if either of those fails, then show the popup and set the cookie (Semi pseudo code):
if($.cookie('popup') != 'seen'){
$.cookie('popup', 'seen', { expires: 365, path: '/' }); // Set it to last a year, for example.
$j("#popup").delay(2000).fadeIn();
$j('#popup-close').click(function(e) // You are clicking the close button
{
$j('#popup').fadeOut(); // Now the pop up is hiden.
});
$j('#popup').click(function(e)
{
$j('#popup').fadeOut();
});
};
You could get around this issue using php. You only echo out the code for the popup on first page load.
The other way... Is to set a cookie which is basically a file that sits in your browser and contains some kind of data. On the first page load you would create a cookie. Then every page after that you check if your cookie is set. If it is set do not display the pop up. However if its not set set the cookie and display the popup.
Pseudo code:
if(cookie_is_not_set) {
show_pop_up;
set_cookie;
}
Offering a quick answer for people using Ionic. I need to show a tooltip only once so I used the $localStorage to achieve this. This is for playing a track, so when they push play, it shows the tooltip once.
$scope.storage = $localStorage; //connects an object to $localstorage
$scope.storage.hasSeenPopup = "false"; // they haven't seen it
$scope.showPopup = function() { // popup to tell people to turn sound on
$scope.data = {}
// An elaborate, custom popup
var myPopup = $ionicPopup.show({
template: '<p class="popuptext">Turn Sound On!</p>',
cssClass: 'popup'
});
$timeout(function() {
myPopup.close(); //close the popup after 3 seconds for some reason
}, 2000);
$scope.storage.hasSeenPopup = "true"; // they've now seen it
};
$scope.playStream = function(show) {
PlayerService.play(show);
$scope.audioObject = audioObject; // this allow for styling the play/pause icons
if ($scope.storage.hasSeenPopup === "false"){ //only show if they haven't seen it.
$scope.showPopup();
}
}
You can use removeItem() class of localStorage to destroy that key on browser close with:
window.onbeforeunload = function{
localStorage.removeItem('your key');
};
The code to show only one time the popup (Bootstrap Modal in the case) :
modal.js
$(document).ready(function() {
if (Cookies('pop') == null) {
$('#ModalIdName').modal('show');
Cookies('pop', '365');
}
});
Here is the full code snipet for Rails :
Add the script above to your js repo (in Rails : app/javascript/packs)
In Rails we have a specific packing way for script, so :
Download the js-cookie plugin (needed to work with Javascript Cokkies) https://github.com/js-cookie/js-cookie (the name should be : 'js.cookie.js')
/*!
* JavaScript Cookie v2.2.0
* https://github.com/js-cookie/js-cookie
*
* Copyright 2006, 2015 Klaus Hartl & Fagner Brack
* Released under the MIT license
*/
;(function (factory) {
var registeredInModuleLoader = false;
if (typeof define === 'function' && define.amd) {
define(factory);
registeredInModul
...
Add //= require js.cookie to application.js
It will works perfectly for 365 days!
You might be using an API for fetching user from database, so use any unique data like id or email or name to identify user then use localstorage method suggested by #Shaunak D. Just replace key with user's unique field and value with popup state.
Like:
ID : popup_state
Sorry for the mistakes in the reply. I am not on my pc today π
π
I have a very basic knowledge of javascript and I have been unable to find a solution for my specific use of the Adobe View SDK API, though it seems like there should be a way. I am working on a web page to show newsletters in the pdf viewer. I have created a w3.css modal element so that I can open the viewer with a button click, and then close it with an "x" in the corner. The button click and the "x" toggle between the display style being "none" or "block". I really like this solution as it lets me use small images of the newsletters as the buttons, and it can be observed here: Test News Page by clicking on the newsletter image below May 4, 2020.
The ultimate goal I have is to be able to change the name of the pdf document that is opened in the viewer by clicking the button, which would need to pass a string variable called "docName" to the url called by the View SDK script. Since the url is already specified in the script inside my modal element when the page loads, here is the thinking I have for the additional script I need to pass my string variables: The button-click invokes my script (function changeName(docName)) and passes the "docName" variable. Then my script needs to pass this variable to the url in the View script (this is the part I don't know how to do), then refresh the page to reload my modal, and then change the display style of the modal to "block". I will copy the code for the View SDK below, showing where I need to insert the string variable with my document name:
<script src="https://documentcloud.adobe.com/view-sdk/main.js"></script>
<script type="text/javascript">
document.addEventListener("adobe_dc_view_sdk.ready", function(){
var adobeDCView = new AdobeDC.View({clientId: "06179511ab964c9284f1b0887eca1b46", divId: "adobe-dc-view"});
adobeDCView.previewFile({
content:{location: {url: "https://www.shcsfarmington.org/" + docName + ".pdf"}},
metaData:{fileName: "Newsletter_050420.pdf"}
}, {embedMode: "FULL_WINDOW", defaultViewMode: "FIT_WIDTH"});
});
</script>
It seems like this should work, but with my limited knowledge of javascript I don't know how to pass this variable to the anonymous function in the View SDK code, and I would need as much detail and specifics in the syntax of the solution. I appreciate any help with this. Thanks.
EDIT: I thought maybe it would help to show the code for the function that I have come up with so far - then it could be examined and easier to debug and comment on:
<button id="CSS-050420" onclick="changeDoc('Newsletter_050420');"></button>
<script>
function changeDoc(docName) {
/* Need to pass docName to url=https://shcsfarmington.org/2020/news/Newsletter_" + newsDate + ".pdf"; */
window.location.reload(true);
document.getElementById('viewerModal').style.display='block';
}
</script>
I created a CodePen here for you to look at.
Basically, you'll load the first file when the SDK is ready but then you need to set the adobeDCView to null before recreating it.
function showPDF(url) {
adobeDCView = null;
fetch(url)
.then((res) => res.blob())
.then((blob) => {
adobeDCView = new AdobeDC.View({
// This clientId can be used for any CodePen example
clientId: "e800d12fc12c4d60960778b2bc4370af",
// The id of the container for the PDF Viewer
divId: "adobe-dc-view"
});
adobeDCView.previewFile(
{
content: { promise: Promise.resolve(blob.arrayBuffer()) },
metaData: { fileName: url.split("/").slice(-1)[0] }
},
{
embedMode: "FULL_WINDOW",
defaultViewMode: "FIT_PAGE",
showDownloadPDF: true,
showPrintPDF: true,
showLeftHandPanel: false,
showAnnotationTools: false
}
);
});
}
The link click even will pass the url to the PDF and then display it.
index.php
<html>
<head>
<title>My Title</title>
<script type="text/javascript">
function getLink(data) {
document.getElementById("box").innerHTML="This is "+data;
}
</script>
</head>
<body>
Home<br />
Profile<br />
Message<br />
Setting<br />
<hr />
<div id="box"></div>
</body>
</html>
Output
Home
Profile
Message
Setting
This is Home
As the code says my Div contents updated when i click any of the link but the problem is that when user goes back by clicking Back Button of Browser the content of my Div donot changes.
I want that either user Goes Back, Goes Forward or he directly puts the path in the address bar www.*****/index.php#profile the content of my Div should be change.
Note
I used document.location.hash to get the value of hash like this :
<head>
<script>
var hashValue=document.location.hash;
alert(hashValue);
</script>
</head>
but it works only when user goes back and then refresh the page
Plz help me how can i achieve this :(
You need to use hashchange event:
function hash_changed() {
var data = document.location.hash.substr(1);
var box = document.getElementById("box");
if (data) {
// inner page
box.innerHTML="This is " + data;
}
else {
// homepage
box.innerHTML = "";
}
}
window.onhashchange = function () {
hash_changed();
};
window.onload = function () {
hash_changed();
};
Also when you are using hashchange event, there is
no need to set onclick for your links:
Home
Profile
Message
Setting
When user click on a link, the hash automatically changes (with href attribute of link),
and hashchange event get fired.
Check DEMO here.
First Time
When a user come to your page for the first time with a hash:
http://fiddle.jshell.net/B8C8s/9/show/#message
We must show the wanted page (message here), so we must run hash_changed() function
we declare above, at first time. For this, we must wait for DOM ready or window.onload.
Check the HTML5 history API. It allows you to work with the browser history
HTML5 history api
$(window).on('hashchange', function() {
alert(location.hash);
});
or window.onhashchange event if you don't want to use jQuery
If you're going to be using AJAX, you'll really want to look into using jQuery instead of raw javascript unless your intention is educational. jQuery is just a mainstay of the web now.
If you must use those hashes...
Use jQuery Special Events, and use the hashchange event:
<a href='#home'>Home</a>
Script:
$(window).on('hashchange', function() {
$('#box').html("This is "+event.fragment);
});
However, for your scenario...
You don't need to use those # values at all as you're passing the values in your function arguments anyway according to the code you provided, just do this:
Home<br />
Alternatively (and preferably, as you're using AJAX according to the tags) you can use jQuery and its builtin selector click events which use Event Listeners:
<a href='javascript:void();' class='divLink' id='home'>Home</a><br/>
Script is this easy:
$('.divLink').click(function(){
$('#box').html("This is "+$(this).id());
}
I have a SharePoint page that has a hyperlink which points to a video clip. Clicking on the link will play the video in an overlay window (uses Silverlight). If Silverlight runtime is not present, it displays the "install Silverlight" prompt. When the page is invoked with a IsDlg=1 query string, the hyperlink is hidden (it is in the left navigation bar), and only the main content page is shown. But I still get the "install Silverlight" prompt. I want to get rid of the prompt when IsDlg=1 is present.
Below is the relevant javascript code on the page. I've modified it slightly to initialize the media player only if IsDlg=1 is not present. But it is not working as expected. Any ideas?
// original code
$(function () {
mediaPlayer.createOverlayPlayer();
mediaPlayer.attachToMediaLinks(document.getElementById('videoList'), ['wmv', 'avi', 'mp4']);
});
// modified code
$(function () {
var field = 'IsDlg';
var url = window.location.href;
if (url.indexOf('?' + field + '=') != -1) {
} else {
mediaPlayer.createOverlayPlayer();
mediaPlayer.attachToMediaLinks(document.getElementById('videoList'), ['wmv', 'avi', 'mp4']);
}
});
As long as the HTML which embeds the Silverlight control is present, it will show the "Install Silverlight" dialog. If you don't want the dialog to show, you'll have to change the HTML source. You could add JavaScript code to add the HTML dynamically, so that it only shows when necessary. That answer would depend on how you're currently embedding the Silverlight control.
EDIT: You could try code like this:
$(function () {
if (window.location.search.indexOf('IsDlg=1') === -1) {
$.getScript('/_layouts/mediaplayer.js', function () {
mediaPlayer.createOverlayPlayer();
mediaPlayer.attachToMediaLinks(document.getElementById('videoList'), ['wmv', 'avi', 'mp4']);
});
}
});
Your code should work, so you probably want to debug for other possible issues.
$(document).ready(function () { // add explicit wait until dom ready
console.log(window.location.search); // just to check that the parameter is present
if(window.location.search.indexOf("IsDlg=1") < 0){ // testing the query string part only
mediaPlayer.createOverlayPlayer();
mediaPlayer.attachToMediaLinks(document.getElementById('videoList'), ['wmv', 'avi', 'mp4']);
}
});
Try that and see how you get on.
I have Drag/Drop functionality in my page embedded using YAHOO.js which is initalized at load of the page. When 'alert' is put in the init function, the Drag/Drop is working otherwise
it is not. Using Firebug I had debugged the code and seen when init function is called but not looping through the function when no alert is put.
This function should work when ALT key is pressed. I am using velocity template engine over JavaScript.
Sample code:
<script type="text/javascript" language="JavaScript">
var myLogger;
var dd1, ddTrashCan; // draggable div objs
#if ($displayOptions.isDoDragDropJavaScript())
YAHOO.util.Event.addListener(window, "load", DD_TestInit);
#end
function display(data) {
var output = "<div>" + data.text + "</div>";
element.innerHTML=output;
}
function DD_TestInit() {
#if ($showLoggerDiv)
initLogger();
#end
//display("date");
initDragObjects();
}
function logMsg(strMsg) {
if (myLogger)
myLogger.debug(strMsg);
}
function initDragObjects() {
//alert('---');
if (dd1) dd1.unreg();
if (ddTrashCan) ddTrashCan.unreg();
YAHOO.util.DDM.mode = YAHOO.util.DDM.POINT;
YAHOO.util.DDM.clickTimeThresh = 10;
## init constant drag objects, draggable div and droppable trash, resp.
dd1 = new lineSched_Draggable("dragDiv1");
ddTrashCan = new lineSched_Droppable("TrashCan");
}
What I had found is whenever I put an alert or call any window.open() this works fine.
Any clue whats happening here.
There is timer event which is delaying the process.My feeling is that this is a timing issue. The page is not fully in place when on load. The alert slows the process down, essentially the page is in place by the time the user clicks Ok on the alert. Clearly, we canβt deploy the app with an alert. But, we can look into different places to put the initialization. We can try to place it the same place I added the timing, when the page receives the last table. The page should be fully formed at this point and the function should work properly.