Extract field value present in javascript of a webpage - javascript

This is the script present in the html web-page.
jQuery(function($) {
new Shopify.OptionSelectors('productSelect', {
product: {
"id":626976579,
"title":"changedMacbook Air",
"handle":"macbook-air",
"description":"\u003cp\u003elightweight \u003c\/p\u003e\n\u003cp\u003eawesome performance\u003c\/p\u003e\n\u003cp\u003ewow display\u003c\/p\u003e\nHello World626976579[\"78000.00\"] [\"78000.00\"]\\n[\"78000.00\"] [\"78000.00\"]\u003cbr\u003e[\"78000.00\"]\u003cbr\u003e626976579\u003cbr\u003e626976579\u003cbr\u003e626976579",
"published_at":"2015-05-25T02:39:00-04:00",
"created_at":"2015-05-25T02:40:44-04:00",
"vendor":"Test_Store",
"type":"Computers",
"tags":[],
"price":7800000,
"price_min":7800000,
"price_max":7800000,
"available":true,
"price_varies":false,
"compare_at_price":null,
"compare_at_price_min":0,
"compare_at_price_max":0,
"compare_at_price_varies":false,
"variants":[{"id":1754837635,"title":"Default Title","options":["Default Title"],"option1":"Default Title","option2":null,"option3":null,"price":7800000,"weight":800,"compare_at_price":null,"inventory_quantity":-29,"inventory_management":null,"inventory_policy":"deny","available":true,"sku":"20","requires_shipping":true,"taxable":true,"barcode":"","featured_image":null}],"images":["\/\/cdn.shopify.com\/s\/files\/1\/0876\/1234\/products\/overview_wireless_hero_enhanced.png?v=1432536113"],"featured_image":"\/\/cdn.shopify.com\/s\/files\/1\/0876\/1234\/products\/overview_wireless_hero_enhanced.png?v=1432536113","options":["Title"],"content":"\u003cp\u003elightweight \u003c\/p\u003e\n\u003cp\u003eawesome performance\u003c\/p\u003e\n\u003cp\u003ewow display\u003c\/p\u003e\nHello World626976579[\"78000.00\"] [\"78000.00\"]\\n[\"78000.00\"] [\"78000.00\"]\u003cbr\u003e[\"78000.00\"]\u003cbr\u003e626976579\u003cbr\u003e626976579\u003cbr\u003e626976579"},
onVariantSelected: selectCallback,
enableHistoryState: true
});
How the value of "title" field be accessed, which here it is "changedMacbook Air" via my own JavaScript?
Thanks in advance.

I don't know if it will work but try
var myProduct = new Shopify.OptionSelectors('productSelect', {
....
})
then try
console.log(myProduct)
or you can try this:
$(document).ready(function(e){
console.log(document.title);
})

I think you might have to pass it through the callback.
$('#productSelect').on('change', function(e) {
var t = e.target || e.srcElement,
title = t.title.value;
selectCallback(title);
break;
}
}
});
//If you want to trigger it right away for some reason, just use this...
$("#productSelect").change();
Look for the code for option_selection.js in your products template or somewhere in your Snippets, Assets, or Templates. See this fiddle for an example of what the code looks like. option_selection.js
You might also want to check this link, it's setting up an onchange event on the product variants. I'm not sure what your ultimate goal is but I see you are working with product options and variants so it might be helpful.
You can modify option_selection.js if you need to, but more than likely you will just need some jquery in the document.ready.
Here is an example from option_selection.js that builds the names of each selector. Though you probably don't need to modify this, see link above.
Shopify.OptionSelectors.prototype.buildSelectors = function() {
for (var t = 0; t < this.product.optionNames().length; t++) {
var e = new Shopify.SingleOptionSelector(this, t, this.product.optionNames()[t], this.product.optionValues(t));
e.element.disabled = !1, this.selectors.push(e)
}
var o = this.selectorDivClass,
i = this.product.optionNames(),
r = Shopify.map(this.selectors, function(t) {
var e = document.createElement("div");
if (e.setAttribute("class", o), i.length > 1) {
var r = document.createElement("label");
r.htmlFor = t.element.id, r.innerHTML = t.name, e.appendChild(r)
}
return e.appendChild(t.element), e
});
return r
},

Related

How to add alt and title attributes along with image in quill editor

var range = this.quill.getSelection();
var value = prompt('please copy paste the image url here.');
if(value){
this.quill.insertEmbed(range.index, 'image', value, Quill.sources.USER);
}
I solved the problem of adding images by linking in the quill editor with the api code above. But I couldn't find how to add alt and title properties with the help of api. I can edit it later with the following javascript code, but I need to edit it at the image insertion stage.
if (e.target.tagName=='IMG') {
console.log(e.target.tagName)
var el = e.target;
el.setAttribute("title", "asdasdasd");
}
})
Also, when I add a or tag to the editor, it is surrounded by a p tag and cannot be edited. It puts everything in the p tag and doesn't allow tags like br. How can I solve these problems?
Sorry for the bad english.
There seems to be no easy and elegant way to do it. The API does not allow it (or I have not seen it) and the source code does not seem to be documented.
I propose this code while waiting for a better solution.
It is based on a solution to observe dynamically created elements. I have added the caption of the title and alt attribute.
To get the code to work, you will need to explain the following to your users:
They must write the title and alt in this format wherever they want to insert the image:
%title% A title %alt% An alternative text
Then, they must select that same:
%title% A title %alt% An alternative text
With that text selected they must click the image button and open the image.
Notice, at the moment, you cannot escape "%alt%", so you cannot use the "%alt%" expression within the value of an attribute.
Example:
%title% The title is before %alt% %alt% the %alt% attribute
This causes an unwanted alt attribute.
Paste this code after creating an editor.
BTW, it is only valid for the first editor that exists.
var FER_alt;
var FER_title;
function FER_callback(records) {
records.forEach(function (record) {
var list = record.addedNodes;
var i = list.length - 1;
for ( ; i > -1; i-- ) {
if (list[i].nodeName === 'IMG') {
if(FER_title.length > 0){
list[i].setAttribute('title',FER_title)
}
if(FER_title.length > 0){
list[i].setAttribute('alt',FER_alt)
}
}
}
});
}
var FER_observer = new MutationObserver(FER_callback);
var FER_targetNode = document.querySelector('.ql-editor')
FER_observer.observe(FER_targetNode, {
childList: true,
subtree: true
});
function FER_getTitleAlt(){
var selection = quill.getSelection();
var texto =quill.getText(selection.index,selection.length);
var titleE = texto.search("%alt%")
FER_title = texto.substr(7,titleE-7);
var titleI = titleE + 5
FER_alt = texto.substring(titleI)
}
var FER_imageboton = document.querySelector(".ql-image")
FER_imageboton.addEventListener("click",FER_getTitleAlt)
Instead of insertEmbed you can use getContents and setContents.
let delta = {
ops: [
{
attributes: {
alt: yourAltValue
},
insert: {
image: yourSrcValue
}
}]
};
let existingDelta = this.quill.getContents();
let combinedDelta = existingDelta.concat(delta);
this.quill.setContents(combinedDelta);
Extends Image blot and override the create method
const Image = Quill.import('formats/image');
class ImageBlot extends Image {
static create(value) {
const node = super.create(value);
if (typeof value === 'string') {
node.setAttribute('src', this.sanitize(value));
node.setAttribute('alt', this.sanitize(value).split('/').reverse()[0]);
}
return node;
}
}
Quill.register(ImageBlot);
In this example, we set alt attribute with image's basename

How to avoid a specific link in Tampermonkey

I've "created" a very small script for automatically clicking links on a specific site using TamperMonkey,
(function() {
'use strict';
var TargetLink = $("a:contains('Click Me')");
if (TargetLink.length)
window.location.href = TargetLink[0].href;
})();
When the link I'm trying to click, looks like this Click Me as an example.
What I'd like for the script to do, is avoid clicking on one specific "ID" and click all the other ones.
Example, I'd like to avoid clicking the ID 1, but click on 2, 3, and 4, where 4 are the amount of total ID's.
Not sure if I explained that as well as I would like to, but hopefully it's somewhat understandable.
You can use .filter() to remove the elements that you don't want.
In the filter I used split and slice to extract the id from href, then I check if the id is in idsBlacklist.
(function() {
'use strict';
var idsBlacklist = [
"1010101"
];
var query = "a:contains('Click Me')";
var TargetLink = $(query).filter(function () {
var id = this.href.split('/').slice(-1)[0];
return idsBlacklist.indexOf(id) < 0;
});
var blackListed = $(query).filter(function () {
var id = this.href.split('/').slice(-1)[0];
return idsBlacklist.indexOf(id) >= 0;
});
if (!blackListed.length && TargetLink.length) {
console.log(TargetLink[0].href);
//window.location.href = TargetLink[0].href;
}
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click Me
Click Me
Click Me

Making dynamically added p elements clickable

I am trying to make the elements clickable. However on clicking any of the <p> elements there is no alert box saying "hello". Please could you look at my code and possibly point me in the right direction?
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
a.onclick = function(e) {
e.preventDefault();
alert("hello");
};
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}
var txtFile8 = new XMLHttpRequest();
txtFile8.open("GET", "http://www.drakedesign.co.uk/mdmarketing/uploads/date.txt", true);
txtFile8.onreadystatechange = function() {
if (txtFile8.readyState === 4) { // Makes sure the document is ready to parse.
if ((txtFile8.status == 200) || (txtFile8.status == 0)) { // Makes sure it's found the file.
allText8 = txtFile8.responseText;
arrayOfLines8 = allText8.match(/[^\r\n]+/g);
for (i = 0; i < arrayOfLines8.length - 1; i++) {
createLink(arrayOfLines8[i], document.getElementById("previousResultsList"));
}
}
}
};
txtFile8.send(null);
The script parses a text file online:
http://www.drakedesign.co.uk/mdmarketing/uploads/date.txt
Which is updated weekly and has dates written in it like so:
19/04/16
12/04/16
...
My script separates the text document into each line and stores it as an array. A for loop is then used to show the dates on the screen in a column which looks like so:
The problem is that on clicking each date an alert box is not shown saying "hello" and there seems to be no response at all.
All help is greatly appreciated.
I solved the issue!!
The problem was that I had divs with opacity 0 that were overlaying my parentElement! sorry stupid mistake!

jQuery appending to a dynamically created div

Trying to add a save/load feature using JSON to a diagram that uses jsPlumb. The save feature works like a charm however the load feature is not able to replicate full initial saved state. That is, the problem occurs when jQuery is trying to append to a freshly/dynamically created div.
The jsfiddle has the following functionality:
I can add projects which are div containers. Inside these I can add tasks by clicking on the green projects.
http://jsfiddle.net/9yej6/1/
My saving code plugins everything into an array which then becomes a string (using JSON).
$('#saveall').click(function(e) {
// Saving all of the projects' parameters
var projects = []
$(".project").each(function (idx, elem) {
var $elem = $(elem);
projects.push({
blockId: $elem.attr('id'),
positionX: parseInt($elem.css("left"), 10),
positionY: parseInt($elem.css("top"), 10)
});
});
// Saving all of the tasks' parameters
var tasks = []
$(".task").each(function (idx, elem) {
var $elem = $(elem);
tasks.push({
blockId: $elem.attr('id'),
parentId: $elem.parent().attr('id')
});
});
// Convert into string and copy to textarea
var flowChart = {};
flowChart.projects = projects;
flowChart.tasks = tasks;
var flowChartJson = JSON.stringify(flowChart);
$('#jsonOutput').val(flowChartJson);
});
The load code does the same in reverse.
$('#loadall').click(function(e) {
// Delete everything from the container
$('#container').text("");
// Convert textarea string into JSON object
var flowChartJson = $('#jsonOutput').val();
var flowChart = JSON.parse(flowChartJson);
// Load all projects
var projects = flowChart.projects;
$.each(projects, function( index, elem ) {
addProject(elem.blockId);
repositionElement(elem.blockId, elem.positionX, elem.positionY)
});
// Try to load all tasks
var tasks = flowChart.tasks;
$.each(tasks, function( index, elem ) {
//Problem occurs here, I am unable to reference the created project
$(elem.parentId).text('This is a test');
addTask(elem.parentId, 0);
});
});
Basically, what's not working is the $(parentId).append(newState); line 75 in the jsFiddle, I can't seem to reference that div because it was just created using jquery ?
edit:
More specifically, I make use of these functions to create actual project and task divs
function addProject(id) {
var newProject = $('<div>').attr('id', id).addClass('project').text(id);
$('#container').append(newProject);
jsPlumb.draggable(newProject, {
containment: 'parent' });
}
function addTask(parentId, index) {
var newState = $('<div>').attr('id', 'state' + index).addClass('task').text('task ' + index);
$(parentId).append(newState);
}
It should be:
$('#' + parentId).append(newState);
To search for an ID in a jQuery selector, you need the # prefix.

What event is triggered when a HTML5 Adobe Extension Panel is collapsed?

I am working on a HTML5 Adobe Extension that needs to load data from LocalStorage into some 's but for the life of me I can't figure out wether the panel is being collapsed or closed or what happens with it. The list items are generated dinamically.
I would also need an ideea to save data upon exit so that the list elements inside the UL can be saved and retrieved when PS starts again. So far I noticed that the host i a chrome type browser that supports a lot of stuff, including localstorage. However, I've not seen a dead simple tutorial for saving ul items but only for variables and strings.
right now I'm unable to save or retrieve the data from localstorage.
here is my code so far.
$(document).ready(function(){
var task = {
"name" : "",
"description" : "",
"project" : ""
};
$('#saveData').css("visibility", "hidden");
$('#btnMarkAsDone').css("visibility","hidden");
var toBeDone = Array();
var wasDone = Array();
$( window ).load(function() {
for(var i = 0;i < toBeDone.length;i++){
$('#todo').append('<li class="todo-item">'+toBeDone[i]+'</li>');
}
for(var i = 0; i < wasDone.length; i++){
$('#done').append('<li class="completed">'+wasDone[i]+'</li>');
}
});
$( window ).width(function() {
});
$("#btnAddTask").click(function(){
var oName = task.name;
var oProject = task.project;
var oDescription = task.description;
var taskname = $("#txtTaskName").val();
var taskproject = $("#txtTaskProj").val();
var taskdescription = $("#txtTaskDesc").val();
oName = taskname;
oProject = taskproject;
oDescription = taskdescription;
var input = "<b>Task: </b>"+oName+" | "+"<b>PSD: </b>"+oProject+" | "+"<b>Desc: </b>"+oDescription;
$("#todo").append('<li class="todo-item">'+input+'</li>');
});
$("#todo").on('click','li',function(){
$(this).addClass('complete');
$("#done").append(this);
});
$("#done").on('click','li',function(){
$(this).remove();
});
$("#saveData").click(function(){
if(localStorage['todo']){
toBeDone = JSON.parse(localStorage['todo']);
}if(localStorage['done']){
wasDone = JSON.parse(localStorage['done']);
}
});
$(function() {
$("button").button();
});
});
Fixed the localStorage part:
$("#saveData").click(function(){
var toDo = $('#todo').html();
var finished = $('#done').html();
localStorage.setItem('todo',toDo);
localStorage.setItem('done',finished);
});
$(window).load(function() {
$("#todo").html(localStorage.getItem('todo'));
$("#done").html(localStorage.getItem('done'));
});
Still need to find out what kind of event is fired when a window is collapsed though. I appreciate any help !

Categories

Resources