I want to add new anchor links to a page using Greasemonkey. Specifically, I want to add custom smileys so that I don't have to find the smiley image and copy-and-paste the link into an [img] tag every time.
The code I want to add is this
<a href="#" onclick="insert_text(':D', true); return false;">
<img src="./images/smilies/icon_e_biggrin.gif" alt=":D" title="Very Happy" height="17" width="15">
</a>
but I want to change the img src location and the onclick to something like
insert_text('[img]imagesourcelocation[/img]' ,true) return false;
The [img] source would be the same as the image URL.
I want to be able to add many smileys over time -- changing the alt and title attributes would be great too, but I need mainly the other two.
How would I do this?
So far all I have is this:
var para=document.createElement("a");
var node=document.createTextNode("This is new.");
para.appendChild(node);
var element=document.getElementById("smiley-box");
element.appendChild(para);
As you can see, I need to add this new smiley to the <div> with the id smiley-box.
If anyone can help me do this I would be so happy.
You can set the properties of DOM element objects by accessing their attributes, e.g. to set the href:
para.href = "#";
Setting the onclick is a bit different - instead of giving it a string of Javascript, you give it a function:
para.onclick = function() {
insert_text('[img]imagesourcelocation[/img]' ,true);
return false;
}
To achieve the image in a link, just create an img element instead of a text node, set it's attributes like above, and add it to the link:
// create the img and set it's src
var node=document.createElement("img");
node.src = "http://upload.wikimedia.org/wikipedia/commons/thumb/8/80/Smiley.png/50px-Smiley.png"
// add the img to the anchor
para.appendChild(node);
Working example here: http://jsfiddle.net/d2gGR/
References:
http://www.w3schools.com/jsref/dom_obj_anchor.asp
http://www.w3schools.com/jsref/dom_obj_image.asp
http://www.w3schools.com/jsref/dom_obj_event.asp
Not sure if this is the greasemoney way but you could also just update the innerHTML of the smiley box directly
function add(url, alt, title)
{
var box=document.getElementById("smiley-box");
box.innerHTML += "<a href=\"#\" onclick=\"insert_text('[img]" + url +
"[/img]', true); return false;\"><img src=\"" + url +
"\" alt=\"" + alt + "\" title=\"" + title + "\" height=\"17\" width=\"15\"></a>";
}
You can then add smileys to the box like this (link, alt text and title text):
add("http://bit.ly/1a4xaTX",":D","Big grin");
add("http://bit.ly/HDGdlw",":(","Sad");
add("http://bit.ly/175LywW",":O","Surprised");
jingtao's solution is a nice one though.
Here's a complete script that adds custom smilies using the awesome power of jQuery. Note that it avoids 3 of the deadly sins of scripting:
It avoids "cut and paste (and cry)" coding.
It uses event handlers the robust web 2.0 way. (Never use onclick.)
It does not trash innerHTML of existing elements.
Additionally, this code is very easy to make AJAX-aware, if needed, using waitForKeyElements().
// ==UserScript==
// #name _Add custom smilies
// #include http://YOUR_SERVER.COM/YOUR_PATH/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js
// #grant GM_addStyle
// ==/UserScript==
/*- The #grant directive is needed to work around a design change
introduced in GM 1.0. It restores the sandbox.
*/
$("#smiley-box").append ('<p>Custom smileys.</p>');
addNewSmiley ("http://sguwars.com/forum/images/smilies/icon_cool.gif");
function addNewSmiley (imageURL) {
$("#smiley-box").append (
'<a href="#" class="gmCustomSmilies">'
+ '<img src="' + imageURL + '"></a>'
);
}
//-- Activate click handlers for any and all of our custom smilies
$(document.body).on ("click", "a.gmCustomSmilies", insertSmilie);
function insertSmilie (evnt) {
var jThis = $(evnt.target);
var imgURL = jThis.find ("img").attr ("src");
unsafeWindow.insert_text ('[img]' + imgURL + '[/img]', true);
return false;
}
var para=document.createElement("p");
var node=document.createTextNode("custom smileys.");
para.appendChild(node);
links = document.createElement('a');
links.setAttribute('href','#');
links.setAttribute('onclick','insert_text(\'[img]http://sguwars.com/forum/images/smilies/icon_cool.gif[/img]\', true); return false;');
links.innerHTML ='<img src="http://sguwars.com/forum/images/smilies/icon_cool.gif" />';
var element=document.getElementById("smiley-box");
element.appendChild(para);
element.appendChild(links);
this is my solution so far thankyou
Related
I'm looking for some help writing a javascript snippet that will DYNAMICALLY update a div style= "background-image:url..." to match the a href above it. This is on a portfolio website, so this is a gallery where all the images are live at once. I need the snippet to run through each individual a href and nested div underneath it and have them match, unique to each image (Don't want a page of the same picture 20 times)
I'm just starting to learn JS, so I've been struggling with this one. Here's the html.
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
This href should from above should be copied to the div style url below.
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
This is what it looks like as a whole...
<a id ="tobematched" href="imgs/galleryphotos/1.jpg">
<div id ="matcher" class="img-container" style="background-image: url('imgs/notcorrect/currently.jpg');"></div>
</a>
Any help would be greatly appreciated!
This is what I'm thinking, so far...
function abc() {
var a = document.getElementById("tobematched").
var b = document.getElementById("matcher").style.backgroundImage;
}
Not sure where to go from here, since I don't know how to grab the href... I think I'm on the right track.
You can use a combination of querySelector() and the .href property to get what you need:
var targetDiv = document.querySelector('#matcher');
var url = targetDiv.parentNode.href;
targetDiv.style.backgroundImage = 'url(' + url + ')';
Alternatively you can use:
var url = document.querySelector('#tobematched').href
This second option does not depend on the structure of the document, but causes JS to look through the whole document again.
If you were using jQuery:
var url = $('#tobematched')attr('href');
$('#matcher').css('background-image', 'url(' + url + ')');
Live Example
Edit: As per the further description by OP in the comments, here is the code you actually need:
var targetDivs = document.querySelectorAll('.img-container');
for (var i = 0; i < targetDivs.length; i++) {
var url = targetDivs[i].parentNode.href;
targetDivs[i].style.backgroundImage = 'url(' + url + ')';
}
I'm trying to create a simple image swapper. So I have 20 images on the page, and 1 large one. I want the user to click one of the smaller images from the 20 and it be output into the place of the big image source.
I've only just started but even so my code doesn't seem to validate as the script fails before it even gets to the console.log. Also not sure if I'm using thisID correctly.
<img id='avatar-output' onclick='selectAvatar(thisID)' src='images/avatars/$number.png' />
<script>
function selectAvatar(thisID){
var imageSource = document.getElementById ("avatar-output").src;
console.log("Avatar source is " imageSource);
}
</script>
HTML:
<img id='avatar-output' src='images/avatars/$number.png' />
<img class='avatar-small' src='images/avatars/1.png' />
<img class='avatar-small' src='images/avatars/2.png' />
<img class='avatar-small' src='images/avatars/3.png' />
JS:
var els = document.getElementsByClassName('avatar-small'),
target = document.getElementById("avatar-output"),
handler = function() { target.src = this.src; };
for (var i=0; i<els.length; ++i) els[i].onclick = handler;
Demo
Or, if all small images are together, better use event delegation:
var target = document.getElementById("avatar-output");
document.getElementById("avatar-small-wrapper").onclick = function(e) {
if(e.target.tagName.toLowerCase() === 'img') target.src = e.target.src;
};
Demo
Notes
Better separation of content (html) and behavior (inline JS)
<script> element needs type="text/javascript" attribute
Avoid running JavaScript in global scope to avoid creating global variables, polluting window. Run in in a closure: (function(){ /* code here */ })()
You have a typo in it, change
var imageSource = document.getElementById ("avatar-output").src;
to
var imageSource = document.getElementById("avatar-output").src;
since there is a space where it shouldn't be.
Edit: oh and another one in the
console.log("Avatar source is " imageSource);
line. Add a + between your string and your variable like this:
console.log("Avatar source is " + imageSource);
I have a function in which when the function is called I need to have text and an image pop up. My javascript is:
function Upload(){
if(value !- ''){
$("#divValue").html("Uploaded: " + //i need to add an image here );
}
So where it says //I need to add an image here, this is where my image, lets say its tire.gif, needs to be added so when the javascript is called it displays the text and image together.
you can use document.createElement method to create a img Object and simply set the source and optional height and width, then add it to your div using "append":
var img = document.createElement('img')
img.src = //URL to your image
$(img).css('width','50px'); //set the width (optional)
$(img).css('height','50px'); //set the height (optional)
//finally append the newly created image object to your "DivValue"
$("#divValue").append(img);
Can you try this,
function Upload(){
var value="some value";
if(value != ''){
$("#divValue").html("Uploaded: <img src='../images/tire.gif' />" );
}
}
It is actually pretty straight forward. You just need to pass the tag inside the string that will replace the html.
Check this jsFiddle
But you just need to do:
$("#divValue").html("Uploaded: <img src=' PATH_TO tire.gif ' /> ");
Watch the difference between " and ' to avoid syntax problems.
Cheers.
You mean like this?
$("#divValue").html('Uploaded: ' + '<img src="image.jpg" alt=""/>');
I'm using a lovely Lightbox plugin that requires the following piece of code per image
<a href="images/portfolio/full/1.jpg"
data-target="flare"
data-flare-plugin="shutter"
data-flare-scale="fit"
data-flare-gallery="portfolio"
data-flare-thumb="images/portfolio/thumbs/1.jpg"
data-flare-bw="images/portfolio/bw/1.jpg"
class="kleur multiple">
<img src="images/portfolio/thumbs/1.jpg" width="375px" height="250px" />
</a>
And I would like to write, together with some of you, a piece of Javascript/jQuery script that elminates writing some of the lines of the above piece of code.
Let me explain: The
- full image (href),
- blackwhite version (data-flare-bw=""),
- lightbox thumb (data-flare-thumb="")
- and the page thumb (<img src=""/>)
all have one thing in common: The filename is identical, only the path differs from eachother. So I would like to write/have a script that, based upon a var it automatically writes those lines of code. Not only the SRC, but also the attribute itself, so the href="", data-flare-bw="", data-flare-thumb="" and the <image src=""/>
As I'm not a Jquery master, i'll try to write down the code that, I'd think somewhat give you guys an idea of what should come:
$function(InsertAttributesAutomaticcly() {
var filenames = $('#container a').attr('data-flare-title', this')
$('#container a').each(function() {
$(this).append('href', 'images/portfolio/full/' + 'filenames' + '.jpg');
$(this).append('data-flare-bw', 'images/portfolio/blackwhite/' + 'filenames' + '.jpg');
$(this).append('data-flare-thumb', 'images/portfolio/thumb/' + 'filenames' + '.jpg');
$(this).html('<img src=" 'images/portfolio/thumb/' + 'filenames' + '.jpg'">');
});
});
Let me explain the code:
It searches within #container for a and then appends the href, data-flare-thumb, data-flare-bw tag to it, with the src/url/href image location, which would be + var (identical to data-flare-title="") + .jpg.
After inserting those three attributes, it inserts a <img> within the a tag, with an src of <path> + var (as before) + '.jpg'
I'm pretty sure this isn't that hard to write, but I'm not that skilled to create a working piece of script, sadly.
Thanks guys!
Bonus task: Those who succesfully write a piece of code above, including a script that tracks the size of the thumb (width + height) and writes that, next to the , will get a beer from me!
Granted that you have such links for example:
<div id="container">
</div>
This would be a viable approach:
$(function(){
$('#container a').each(function(){
var $link = $(this),
title = $link.data('flare-title');
$link.attr('href', 'images/portfolio/full/' + title);
$link.attr('data-flare-bw', 'images/portfolio/blackwhite/' + title);
$link.attr('data-flare-thumb', 'images/portfolio/thumbs/' + title);
$link.append($('<img>', {
src : 'images/portfolio/thumbs/' + title,
width : '375px',
height : '250px'
}));
});
});
Edit: see fiddle.
I'm trying to add some html markup to the WYSIWYG CLEditor from outside of the editor itself using jQuery.
So far I have...
$('.add-image').click(
function()
{
theurl = $(this).text();
theimage = '<img src="' + theurl + '" />';
// Now What?
}
);
But I'm at a loss as to how to add the string in to the WYSIWYG and it's starting to drive me crazy!
This will overwrite:
$("#inputID").val(theimage);
$("#inputID").cleditor()[0].updateFrame();
This will append:
currentval = $("#inputID").val();
$("#inputID").val(theimage);
$("#inputID").val(currentval + theimage);
Or maybe try this:
$('#inputID').val('new text data').blur();
Where inputID is the ID of your CLEditor input.
Also, this has some discussion around this:
CLEditor dynamic adding text
Just made 2 small edits to CCCasons solution to make it work as intended.
$('.add-image').click(
function()
{
theurl = $(this).text();
theimage = '<img src="' + theurl + '" /><br/>';
// Get the current value of the textarea otherwise it will be overwritten
currentval = $("textarea.wysiwyg").val();
$("textarea.wysiwyg").val(currentval + theimage);
$("textarea.wysiwyg").cleditor()[0].updateFrame();
}
);
1) Added a line break to the end of the inserted link. Otherwise when you try to type in the wysiwyg after adding the image it inputs inside the link.
2) Grabbed the current value of the textarea first to stop it being overwritten by the image.
Again, thanks a lot to CCCason!