Edit src of img with codemirror - javascript

I'm trying to update the src attribute of <img> tags so that the user can insert images to the code from our asset manager.
Consider this HTML:
<div>
<img src="some_image_already_defined.jpg" alt="Some Image" />
</div>
So if the user places the cursor to any position inside the img tag, I'll replace "some_image_already_defined.jpg" with the new image user selected.
The simplified version of code is smt. like that:
var image_path = 'some_new_image.jpg';
$('#insert-image').click(function() {
var cur = codeMirrorHtml.getCursor();
var token = codeMirrorHtml.getTokenAt(cur);
var inner = CodeMirror.innerMode(codeMirrorHtml.getMode(), token.state);
if (inner.state.tagName == 'img') {
var srcPosition = findTheSrcAttributePosition(); // How do I do this?
codeMirrorHtml.setSelection(srcPosition.anchor, srcPosition.head);
codeMirrorHtml.replaceSelection('src="' + image_path + '"');
}
});
So I want to traverse the token somehow but I couldn't find a way to do it.

Step 1
Get the current line number with getCursor:
var line = editor.getCursor().line;
Step 2
Get the contents of the current line using getLine:
var lineTxt = editor.getLine(line);
Step 3
Find the <img tag. This is just a string search and it's up to you:
var imgTagStartIdx = lineTxt.indexOf("<img");

Related

How to render html partially inside div?

I have a div and I want to set some text inside this div. Problem is my text contains HTML elements and I don't want all these elements to be rendered. I mean some elements must rendered as HTML.
Is there any way to create a div content like this?
I want to create a div element like below;
<div id="bodyContent">
</div>
Setting with html method is not working.
var myHTMLContentPart1 = "<HTML><BODY>";
var myHTMLContentPart2 = "<span>hello</span>";
var myHTMLContentPart3 = "</BODY></HTML>";
$("#bodyContent").html(?);
EDIT:
I recommend you to use regex to remove html or body tags, also you can add any tag that you want to remove like this <\/?tagname>
html = '<html><body><span>Some Text</span></body></html>';
clean = html.replace(/<\/?html>|<\/?body>/g, '');
console.log(clean);
// For your code
var myHTMLContentPart1 = "<HTML><BODY>";
var myHTMLContentPart2 = "<span>hello</span>";
var myHTMLContentPart3 = "</BODY></HTML>";
var html = myHTMLContentPart1 + myHTMLContentPart2 + myHTMLContentPart3;
clean = html.replace(/<\/?html>|<\/?body>/g, '');
$("#bodyContent").html(clean);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="bodyContent">
</div>

Javascript: inserting a variable as a parameter

I am looking at getting my "NodeNumber" variable into the parameter of my loadSynchPage function.
my code looks at the name of the page (e.g. page.htm from http://www.example.com/tree/page.htm) and after a series of lines gives a "NodeNumber". I would like the page to work out the NodeNumber and put it into the function when the page loads.
So I'd guess it would look something like this:
<BODY onload="loadSynchPage(NodeNumber);">
I have got my code to output the NodeNumber using a button with onlick.
I have also got the loadSynchPage(linkID) function, to work using a button with onclick where I enter the number myself. button and have also got a variable which I predefine to work; but I can't get it to read my "NodeNumber" and I have spent 2 days trying to figure this out.
Here is my code:
<script>
function variables() {
//Getting the page's name from the URL
PageName = location.pathname.split("/").slice(-1);
document.getElementById("PageName").innerHTML = PageName;
//Converting the page name into a string
PageNameString = String(PageName);
document.getElementById("PageNameString").innerHTML = PageNameString;
//Converting the string of the page name, into it's length
PageLength = PageNameString.length;
document.getElementById("PageLength").innerHTML = PageLength;
//Setting the DemoFramesetNodes.js as a variable (Copy and Paste in - needs to have no " and be on one line)
TextFromDemoFramesetNodesJS = "foldersTree = gFld(<i>Page 1 Title</i>, page1.htm)//000foldersTree.treeID = Framesetaux1 = insFld(foldersTree, gFld(Page 2 Title, page 2.htm)) //001insDoc(aux1, gLnk(R, Page 3 Title, Page3.htm)) //002aux1 = insFld(foldersTree, gFld(Page 4 Title, Page4.htm)) //003insDoc(aux1, gLnk(R, Page 5 Title, Page5.htm)) //004";
//Need to set the difference BETWEEN the "m" in htm and the start of the number
//e.g. page2.htm)) //001
CharacterDifference = "5";
document.getElementById("CharacterDifference").innerHTML = CharacterDifference;
//Need to find the location of the page's name from the DemoFramsetNodes
PageNameLocation = TextFromDemoFramesetNodesJS.lastIndexOf(PageNameString);
document.getElementById("PageNameLocation").innerHTML = PageNameLocation;
//Need to convert all variables to be added into numbers
PageNameLocationNumber = Number(PageNameLocation);
PageLengthNumber = Number(PageLength);
CharacterDifferenceNumber = Number(CharacterDifference);
document.getElementById("CharacterDifferenceNumber").innerHTML = CharacterDifferenceNumber;
//Add the variables to give us the start location of the Node Number
NodeNumberStart = PageNameLocationNumber + PageLengthNumber + CharacterDifferenceNumber;
document.getElementById("NodeNumberStart").innerHTML = NodeNumberStart;
//Add the variables to give us the end location of the Node Number
NodeNumberEnd = PageNameLocationNumber + PageLengthNumber + CharacterDifferenceNumber + 3;
document.getElementById("NodeNumberEnd").innerHTML = NodeNumberEnd;
//this gives us the Node Number that we want
NodeNumber = TextFromDemoFramesetNodesJS.substring(NodeNumberStart, NodeNumberEnd);
document.getElementById("NodeNumber").innerHTML = NodeNumber;
}
var avar=Number(window.NodeNumber);
//window.NodeNumber;
function loadSynchPage(linkID) {
var folderObj;
docObj = parent.treeframe.findObj(linkID);
docObj.forceOpeningOfAncestorFolders();
parent.treeframe.HightlightNode(linkID,docObj.link,'basefrm');
if (typeof parent.treeframe.document.body != "undefined") // To handle scrolling not working with NS4
parent.treeframe.document.body.scrollTop=docObj.navObj.offsetTop
}
//myvar=Number(NodeNumber);
// function loadnode(){
// document.getElementById('loadSynchPage').onclick=function(){loadSynchPage(myvar);};
// var myvar=15;
//function init(){
// document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
// }
</script>
</head>
<BODY>
<button onclick="javascript:settingvariables();">Page Highlight1</button>
<button onclick="javascript:loadSynchPage(avar);">Page Highlight2</button>
Page Name: <p id="PageName"></p>
Page Name String: <p id="PageNameString"></p>
Page Length: <p id="PageLength"></p>
Character Difference: <p id="CharacterDifference"></p>
Page Name Location: <p id="PageNameLocation"></p>
Character Difference Number:<p id="CharacterDifferenceNumber"></p>
Node Number Start: <p id="NodeNumberStart"></p>
Node Number End: <p id="NodeNumberEnd"></p>
Node Number: <p id="NodeNumber"></p>
As you can see from the "//" near the bottom, I have already tried some different ways from other questions on stackoverflow - I am sure I have tried everything and am missing something really simple :/
I have also taken out the "var" before setting things like PageName and NodeNumber after w3 said that this would then allow them to become global variables?
To give more information:
The code is based on TreeView - it has a tree with nodes on the left and you click on the nodes to open the page in the right hand frame. However clicking on a link from a page in the right page to a different page doesn't update the highlighting on the node and that is why I am trying to do this (onload).
EDIT: If possible I would also like to get the code into an external .js and reference it as I have multiple pages (I tried this for a few hours last week with different, working code, but also couldn't get this to work either).
All you need is:
window.onload = function() {
loadSynchPage(NodeNumber);
};
Or the onload in body tag, the problem you have is that it doesn't work in the sandbox in this snippet:
Uncaught SecurityError: Sandbox access violation: Blocked a frame at
"http://stacksnippets.net" from accessing a frame at
"http://stackoverflow.com". The frame requesting access is sandboxed
and lacks the "allow-same-origin" flag.
function variables() {
//Getting the page's name from the URL
PageName = location.pathname.split("/").slice(-1);
document.getElementById("PageName").innerHTML = PageName;
//Converting the page name into a string
PageNameString = String(PageName);
document.getElementById("PageNameString").innerHTML = PageNameString;
//Converting the string of the page name, into it's length
PageLength = PageNameString.length;
document.getElementById("PageLength").innerHTML = PageLength;
//Setting the DemoFramesetNodes.js as a variable (Copy and Paste in - needs to have no " and be on one line)
TextFromDemoFramesetNodesJS = "foldersTree = gFld(<i>Page 1 Title</i>, page1.htm)//000foldersTree.treeID = Framesetaux1 = insFld(foldersTree, gFld(Page 2 Title, page 2.htm)) //001insDoc(aux1, gLnk(R, Page 3 Title, Page3.htm)) //002aux1 = insFld(foldersTree, gFld(Page 4 Title, Page4.htm)) //003insDoc(aux1, gLnk(R, Page 5 Title, Page5.htm)) //004";
//Need to set the difference BETWEEN the "m" in htm and the start of the number
//e.g. page2.htm)) //001
CharacterDifference = "5";
document.getElementById("CharacterDifference").innerHTML = CharacterDifference;
//Need to find the location of the page's name from the DemoFramsetNodes
PageNameLocation = TextFromDemoFramesetNodesJS.lastIndexOf(PageNameString);
document.getElementById("PageNameLocation").innerHTML = PageNameLocation;
//Need to convert all variables to be added into numbers
PageNameLocationNumber = Number(PageNameLocation);
PageLengthNumber = Number(PageLength);
CharacterDifferenceNumber = Number(CharacterDifference);
document.getElementById("CharacterDifferenceNumber").innerHTML = CharacterDifferenceNumber;
//Add the variables to give us the start location of the Node Number
NodeNumberStart = PageNameLocationNumber + PageLengthNumber + CharacterDifferenceNumber;
document.getElementById("NodeNumberStart").innerHTML = NodeNumberStart;
//Add the variables to give us the end location of the Node Number
NodeNumberEnd = PageNameLocationNumber + PageLengthNumber + CharacterDifferenceNumber + 3;
document.getElementById("NodeNumberEnd").innerHTML = NodeNumberEnd;
//this gives us the Node Number that we want
NodeNumber = TextFromDemoFramesetNodesJS.substring(NodeNumberStart, NodeNumberEnd);
document.getElementById("NodeNumber").innerHTML = NodeNumber;
}
var avar=Number(window.NodeNumber);
//window.NodeNumber;
function loadSynchPage(linkID) {
alert("loadSynchPage called");
var folderObj;
docObj = parent.treeframe.findObj(linkID);
docObj.forceOpeningOfAncestorFolders();
parent.treeframe.HightlightNode(linkID,docObj.link,'basefrm');
if (typeof parent.treeframe.document.body != "undefined") // To handle scrolling not working with NS4
parent.treeframe.document.body.scrollTop=docObj.navObj.offsetTop
}
loadSynchPage(NodeNumber);
//myvar=Number(NodeNumber);
// function loadnode(){
// document.getElementById('loadSynchPage').onclick=function(){loadSynchPage(myvar);};
// var myvar=15;
//function init(){
// document.getElementById('EditBanner').onclick=function(){EditBanner(myvar);};
// }
<button onclick="javascript:settingvariables();">Page Highlight1</button>
<button onclick="javascript:loadSynchPage(avar);">Page Highlight2</button>
Page Name: <p id="PageName"></p>
Page Name String: <p id="PageNameString"></p>
Page Length: <p id="PageLength"></p>
Character Difference: <p id="CharacterDifference"></p>
Page Name Location: <p id="PageNameLocation"></p>
Character Difference Number:<p id="CharacterDifferenceNumber"></p>
Node Number Start: <p id="NodeNumberStart"></p>
Node Number End: <p id="NodeNumberEnd"></p>
Node Number: <p id="NodeNumber"></p>
2nd question: Save all the script (not including the <script> tags) to myjs.js, put it to the same directory next to page.html, and remove the whole <script> block from html, and put this instead of it:
<script src="myjs.js"></script>

Fetching values from an element in an iframe on the same domain

I'm trying to condense two processes down in to one by having the two pages I need on one page using an iframe.
I have a page that contains a text area (used for sending an email) and then I have a purchase reference page that contains the details of someones purchase.
I'm trying to append an iframe of the purchase page to the bottom of my email page and then grab some data that's on it and insert it in to the text area.
EDIT: This is what I have so far:
Script one
//Grabs the selected purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
var purchaseTitle;
var purchaseNumber;
function frameLoaded() {
purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
}
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe));
alert(purchaseNumber);
}
Script Two
//Gather the selected template
var selectedTxt = document.getElementById('txtEmailText').value;
//Change the selected txt to a string
var insertText = selectedTxt.toString();
var purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
var purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;
Effectively I am highlighting the purchase reference number on the page then executing this script to open the purchase page using the highlighted number. I am then grabbing the text values of the elements I need and pasting them in to the text area.
I'm still pretty new to javascript and am teaching myself as I go.
If i run the above scripts one after the other then it works like a charm, however if I try to run them together with the second in an onload() function set to the iframe then it won't.
Any help would be greatly appreciated or if you could point me in the direction of an article to help.
My first thought is that the iframe is not fully loaded before you try to get the values from it. My thought would be to try adding an onload event to your iframe and then when it loads invoke a function that grabs the value.
I would add purchaseIframe.setAttribute("onload", "frameLoaded();"); to your purchaseIframe block and then add the frameLoaded() function to your script. something like:
function frameLoaded() {
var purchaseTitle = window.frames[0].document.getElementById("listingTitle" );
var purchaseNumber = window.frames[0].document.getElementById("auctionSoldIdDisplay");
console.log(purchaseTitle.innerHTML);
console.log(purchaseNumber.innnerHTML);
}
And see if something like that grabs the right values. If it does than you can plug it in where you need it.
Am I understanding your problem correctly?

Modifying src attr using replace

Hello i made a code where i get the last part of the src data and replace _t for empty space like this.
// Get the current image number
var current = $(next.index("img"));
var nextUrl = next.attr("src").replace("_t", "");
This is the img example
<img src="http://farm1.static.flickr.com/28/66523124_b468cf4978_t.jpg" />
so in the example case i get this URL
http://farm1.static.flickr.com/28/66523124_b468cf4978
My question is ... I have to modify that code to actually change that at the beginin of the URL
in the Script im working now the thums are
<img id="extra_15" src="data/16/t_15_images.jpg" border="0" width="70px" class="">
And the big images are
<img id="extra_15" src="data/16/15_images.jpg" border="0" width="70px" class="">
how do i change that?
Switch around the pattern you are looking for. Instead of _t do t_.
var nextUrl = next.attr("src").replace("t_", "");

Parse text in TextArea and display images based on the path

I am having a HTML5 webpage.
In which I am having a TextArea with some raw data.
say something like this.
Image1:
C:\Images\image1.jpg
Image2:
C:\Images\image2.jpg
Image3:
C:\Images\image3.jpg
I need to parse that textarea and show images in the path below the textarea.
I need to pass that path to the img src="path" tag and i should display the images based on the paths in textarea.
Any help would be appreciated!!
I put together a JSFiddle (http://jsfiddle.net/jt5yg/6) to do this. The HTML and Javascript were fairly simple:
<textarea id="rawdata" rows="10" style="width: 100%" onchange="processimages();">
</textarea>
<div id="images"></div>
and
var allfiles = /[a-z]\:\\[\w\\_-]+?\.jpg/gi;
function processimages(){
var textarea = document.getElementById('rawdata');
var imagecontainer = document.getElementById('images');
var file;
imagecontainer.innerHTML = '';
while(file = allfiles.exec(textarea.value)){
imagecontainer.innerHTML += '<img src="file:///'+file+'" />';
}
}
Unfortunately, when I ran the script, the image tags were added, but the browser refused to display them. Security restrictions prevent the browser from accessing the local file system without explicit user action.
This makes sense, of course. If we could do this, hackers could access the contents of hidden system files on your PC the same way.
With jQuery it can be like this:
var sText = jQuery('textarea_selector').text(),
aStrings = sText.split('\n');
for(i = aStrings.length - 1; i>=0; i--) {
if( aStrings[i].indexOf('\\') != -1 ) {
jQuery('body').append('<img src="'+aStrings[i]+'">');
}
}
var srcs = $('textarea').val().replace(/\\/g, "||");
srcs = srcs.split(/Image\d:/).map(function(el) {
return el.replace("||", "\\");
});
srcs[0] // C:\Images\image1.jpg
You can now iterate over the array and apply src to each Img.

Categories

Resources