I have a after effects bodymovin.js SVG animation with ID's on certain paths (image attached). I've put some css styles on these (cursor:pointer), which work fine but using jquery onClick for a redirect doesn't seem to be working. Any ideas why?
The animation itself is in an overlay which starts after a button is pressed.
The redirect code:
<script>
$(function() {
document.getElementById("replay").onclick = function () {
location.href = "www.yoursite.com";
};
});
</script>
The animation code:
<script>
$( ".animation" ).click(function() {
var anim;
var elem = document.getElementById('bodymovin_overlay')
var animData = {
container: elem,
renderer: 'svg',
loop: false,
autoplay: true,
rendererSettings: {
progressiveLoad:false
},
path: 'data_overlay.json'
};
anim = bodymovin.loadAnimation(animData);
});
</script>
Also the image is attached:
Remove # from document.getElementById("#replay").
Use document.getElementById("replay") (Native JS) or via jQuery $('#replay')
I believe the error occurs because you forgot to add a semi-colon.
var elem = document.getElementById('bodymovin_overlay')
to
var elem = document.getElementById('bodymovin_overlay');
Issue solved - the overlay was covering the animations z-index, had to give it a higher z-index than the overlay.
Final code that worked, hope it helps someone:
var lookingForLinks = true;
setTimeout(addLinksToSvgAnim, 1000);
function addLinksToSvgAnim() {
if (lookingForLinks) {
let medicalG = document.getElementById("medical");
let foodG = document.getElementById("food");
let collabG = document.getElementById("collab");
let volunteersG = document.getElementById("volunteers");
let projectsG = document.getElementById("projects");
let replayG = document.getElementById("replay");
if (medicalG && foodG && volunteersG && projectsG) {
lookingForLinks = false;
medicalG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/medical-aid";
});
foodG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/humanitarian-aid";
});
collabG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/our-story/partners";
});
volunteersG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/get-involved";
});
projectsG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/bringhope-projects";
});
replayG.addEventListener("click", function () {
window.location = window.location.protocol + "//" + window.location.hostname + "/bringhope-projects";
});
}
setTimeout(addLinksToSvgAnim, 1000);
}
}
Related
I have this script but its only share from mobile version.
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
var whatsapp_url = ".whatsapp://send?text=" + message;
window.location.href = whatsapp_url;
} else {
alert("Please use an Mobile Device to Share this Status");
}
});
});
Can anyone modify this?
This line
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
checks for mobile and if true, the share logic is executed. In the else branch (meaning it's not a mobile) you get an error message. If you want the same to happen in both versions, just omit the if:
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
//if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
var whatsapp_url = ".whatsapp://send?text=" + message;
window.location.href = whatsapp_url;
//} else {
//alert("Please use an Mobile Device to Share this Status");
}
});
});
According the WhatsApp docs: https://faq.whatsapp.com/general/chats/how-to-use-click-to-chat/?lang=en
To create a link with just a pre-filled message, use https://wa.me/?text=urlencodedtext
Example: https://wa.me/?text=I'm%20inquiring%20about%20the%20apartment%20listing`
The result should be something like:
$(document).ready(function() {
$(document).on("click", '.mc_whatsapp_btn', function() {
// this 3 rows will be used for both - desktop and mobile
var text = $(this).attr("data-text");
var url = $(this).attr("data-link");
var message = encodeURIComponent(text) + " - " + encodeURIComponent(url);
if (/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) {
var whatsapp_url = ".whatsapp://send?text=" + message;
} else {
var whatsapp_url = "https://wa.me/?text=" + message;
}
// again for both
window.location.href = whatsapp_url;
});
});
Could someone help me. Because I'm just started learning JavaScript.
I'm using a custom prompt dialog, before it's working when I use XMLHttpRequest
But, I want to use "Fetch" instead because it's the new one and better.
with using Fetch the dialog is not showing and I'm getting error "layer is not defined"
Here's my little question, How I can call it properly the layer.js and layer.css from the response?
I'm calling it like this (this is a message dialog):
layer.open({
title: "<strong>" + formTitle + "</strong>",
content: "<strong>" + msg + "</strong>",
maxWidth: 500,
});
Here's my code.
!function () {
try {
if (typeof (eval(layer)) == "function") { }
} catch (e) {
var css = 'https://cdn.bootcss.com/layer/3.0.1/skin/default/layer.css';
var js = 'https://cdn.bootcss.com/layer/3.0.1/layer.min.js';
var a = document.createElement("style");
a.type = "text/css";
DownloadStringAsync(css).then(_css => a.innerText = _css);
document.getElementsByTagName("head")[0].appendChild(a)
var a = document.createElement("script");
DownloadStringAsync(js).then(_js => a.text = _js);
document.getElementsByTagName("head")[0].appendChild(a)
}
var url = amp.mediaProxy.facade.config.media.originalSrc;
var title = ampl_title;
var formTitle = "Url Parser v1.0";
var msg = `${title}<br>${GetTitle()}<br>`;
try {
var fileName = `TEST.txt`;
SaveToFileAsync(url, fileName);
} catch (err) {
layer.open({
title: "Error",
content: err.message
});
}
layer.open({
title: "<strong>" + formTitle + "</strong>",
content: "<strong>" + msg + "</strong>",
maxWidth: 500,
});
async function DownloadStringAsync(url) {
let response = await fetch(url, {
method: "GET",
cache: "no-cache",
});
let data = await response.text()
return data;
}
function SaveToFileAsync(url, filename) {
fetch(url, {
method: "GET",
cache: "no-cache",
}).then(async function (t) {
const b = await t.blob();
var a = document.createElement("a");
a.href = URL.createObjectURL(b);
a.setAttribute("download", filename);
a.click();
});
}
function GetTitle() {
return document.getElementsByClassName("hero-image-rating eps-line")[0].innerText + "\n";
}
}();
I am trying to develop a chrome extension which parses data from the current tab and post it to a url which does processing on the data. In certain cases the page may need to be redirected so that certain get parameters are present. My popup.js can successfully do the redirect, but I need to click on the extension a second time to get it to run properly. Note: it runs properly if the page has the correct parameters. How can I adjust this so that the code reruns after the redirect and posts the new source to the specified url.
Here is my popup.js:
var url = "";
chrome.runtime.onMessage.addListener(function(request, sender) {
chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, function (tabs) {
url = tabs[0].url;
if (url.search("[?&]view=list") == -1)
{
url = setGetParameter(url,'view','list');
chrome.tabs.update(tabs[0].id,{url:url});
process(request);
}
});
process(request);
});
function process(request) {
if (request.action == "getSource") {
message.innerText = request.source;
var data = new FormData();
data.append('source',request.source);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == XMLHttpRequest.DONE) {
message.innerText = xhttp.responseText;
}
}
xhttp.open("POST","http://127.0.0.1:5000/api/scraper",true);
xhttp.send(data);
}
}
function onWindowLoad() {
var message = document.querySelector('#message');
chrome.tabs.executeScript(null, {
file: "getPagesSource.js"
}, function() {
// If you try and inject into an extensions page or the webstore/NTP you'll get an error
if (chrome.runtime.lastError) {
message.innerText = 'There was an error injecting script : \n' + chrome.runtime.lastError.message;
}
});
}
function setGetParameter(url, paramName, paramValue)
{
var hash = location.hash;
url = url.replace(hash, '');
if (url.indexOf(paramName + "=") >= 0)
{
var prefix = url.substring(0, url.indexOf(paramName));
var suffix = url.substring(url.indexOf(paramName));
suffix = suffix.substring(suffix.indexOf("=") + 1);
suffix = (suffix.indexOf("&") >= 0) ? suffix.substring(suffix.indexOf("&")) : "";
url = prefix + paramName + "=" + paramValue + suffix;
}
else
{
if (url.indexOf("?") < 0)
url += "?" + paramName + "=" + paramValue;
else
url += "&" + paramName + "=" + paramValue;
}
return url + hash;
}
window.onload = onWindowLoad;
Take a look at webRequest.onBeforeRedirect, this event fired when a redirect is about to be executed. You can listen to this event and do your logic again.
Don't forget to declare webRequest permission along with host permissions for any hosts whose network requests you want to access in you manifest.json.
This question already has answers here:
jQuery Deferred - waiting for multiple AJAX requests to finish [duplicate]
(3 answers)
Closed 6 years ago.
I'm trying to execute a callback after multiple jQuery Ajax have completed.
In my code both Ajax requests call another function and when I try to use these functions I get undefined.
I think the problem has to do with using deferred/promise, but I don't know how to use them.
Here is my code:
<link rel="stylesheet" type="text/css" href="https://tag/sites/ocean1/maker/captions/shared%20documents/Web_ComplianceCSS.txt">
<div id = "cabbage" style="font-size:10px">
<p>Web Compliance Stats</p>
</div>
<script type = "text/javascript">
var WebComplianceReportApp = {} || WebComplianceReportApp;
WebComplianceReportApp.GetStatuses = (function() {
var pub = {},
_userId,
_ultimateObjectHolderArr = [],
_items = [],
_options = {
listName: "M_Web_Compliance",
container: "#cabbage",
};
pub.init = function() {
var clientContext = new SP.ClientContext.get_current();
_userId = clientContext.get_web().get_currentUser();
clientContext.load(_userId);
clientContext.executeQueryAsync(getUserInfo, _onQueryFailed);
};
function getUserInfo() {
_userId = _userId.get_id();
getSpecifiedList(_options.listName, _userId);
}
function buildObject(results, listName) {
_items = results.d.results;
$.each(_items, function(index, item) {
_ultimateObjectHolderArr.push({
"Division": item.ParentOrg,
"ORG": item.ORG,
"URL": item.URL,
"Status": item.Site_Status
});
});
//createStatusView2(_ultimateObjectHolderArr);
}
function getSpecifiedList(listName, userId) {
var counter = 0;
var baseUrl = SP.PageContextInfo.get_webServerRelativeUrl() + "/_vti_bin/listdata.svc/" + listName;
var url1 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages";
var call1 = $.ajax({
url: url1,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
var url2 = baseUrl + "?$select=ParentOrg,ORG,URL,Site_Status&$inlinecount=allpages&$skiptoken=1000";
var call2 = $.ajax({
url: url2,
type: "GET",
headers: {
"accept": "application/json;odata=verbose",
}
}).done(function(results) {
buildObject(results, listName);
}).fail(function(error) {
console.log("Error in getting List: " + listName);
$(_options.container).html("Error retrieving your " + listName + ". " + SP.PageContextInfo.get_webServerRelativeUrl());
});
}
function createStatusView2(Arr) {
var divisionArr = [];
var oRGArr = [];
var divisionCount = 0;
var oRGCount = 0;
for (var i = 0; i < Arr.length; i++) {
if ($.inArray(Arr[i].Division, divisionArr) === -1) {
divisionArr.push(Arr[i].Division);
var divisionHolderElement = $("<div id='p_" + Arr[i].Division + "' class='division_row_holder'></div>");
var divisionElement = $("<div id='" + Arr[i].Division + "' class='division_div ORG'></div>").text(Arr[i].Division);
$("#cabbage").append(divisionHolderElement);
$(divisionHolderElement).append(divisionElement);
}
if ($.inArray(Arr[i].ORG, oRGArr) === -1) {
oRGArr.push(Arr[i].ORG);
var orgElement = $("<div class='org_div ORG' id='" + Arr[i].ORG + "' style='font-size:10px;'></div>").text(Arr[i].ORG);
$("#p_" + Arr[i].Division).append(orgElement);
}
}
}
//automatically fired by init
function _onQueryFailed(sender, args) {
alert('Request failed.\nError: ' + args.get_message() + '\nStackTrace: ' + args.get_stackTrace());
}
return pub
}());
$(document).ready(function() {
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', function() {
//After the SP scripts are run, we access the WebComplianceReportApp.GetStatuses
WebComplianceReportApp.GetStatuses.init();
});
});
</script>
I dont know if this will make your code dirty, but I would use a flag in this case
ex:
var ajaxCalls = 0;
function checkAjaxCalls()
{
if (ajaxCalls == 2)
{
//do your thing...
//and maybe you want to reset ajaxCalls value to zero if needed...
}
}
And from each Ajax response completes, increment ajaxCalls variable by one, and call the checkAjaxCalls function from both your Ajax responses.
Method One:
This time we'll have waited for the request to complete instead of waiting for the request to succeed
$(".ajax-form-button-thingy").on("click", function() {
$.ajax({
url: $(this).attr("href"),
type: 'GET',
error: function() {
throw new Error("Oh no, something went wrong :(");
},
complete: function(response) {
$(".ajax-form-response-place").html(response);
}
});
});
Method Two:
If you want to wait for ALL Ajax requests to complete without changing the async option to false then you might be looking for jQuery.ajaxComplete();
In jQuery every time an Ajax request completes the jQuery.ajaxComplete(); event is triggered.
Here is a simple example but there is more info on jQuery.ajaxComplete(); over here.
$(document).ajaxComplete(function(event, request, settings) {
$(".message").html("<div class='alert alert-info'>Request Complete.</div>");
});
Also you can take a look at the Ajax response by using request.responseText this might be useful in case you want to double check the response.
For more information about jQuery.ajax you can read the docs here
You could call createStatusView(); and then call createStatusView2(); after all of your Ajax requests are done
$(document).ready(function(){
createStatusView();
$(this).ajaxStop(function() {
// NOTE: I did not see you use createStatusView(); in your code
createStatusView2();
});
});
How do get the hash url to output something cleaner? Its doing this:
domain.com/#/page/1
When I want it to do this:
domain.com/page/1
$(document).ready(function(){
var newHash = '';
$('#wrapper a').live('click', function(e){
if (this.hostname && this.hostname == location.hostname) {
e.preventDefault();
var link = $(this).attr('href');
window.location.hash = link;
}
});
$(window).bind('hashchange', function() {
newHash = window.location.hash.substr(1);
$('#content').fadeOut(100).load(newHash + ' #contentInner', function(){
$('#content').fadeIn(100);
});
});
});
Try :
var url = "domain.com/#/page/1";
var noHash = url.split("/#").join("");
That's what a hash is supposed to look like - the # portion is the hash. If you don't want a hash in your url, then do:
window.location = link;
instead.
if (location.href.indexOf("#") > -1) {
location.assign(location.href.replace(/\/?#\//, "/"));
}