I know it has been posted before on how to append only once, but my situation is a little unique because I'm attempting to call the function from an href link. I have my code posted on jsfiddle, but it's not working for some reason. The same code on my site works. Can someone help me get this working so that clicking the href link will append a given string to the #services div only one time. The code thats on my actual site appends the "details" over and over again every time I click the link, but I only want it to do it once.
<div id="services">SERVICES</div>
More Details
var details = '<p>Just some additional details</p>';
function moreDetails(){
$('#services').append(details);
}
http://jsfiddle.net/7g59yb5r/1/
I'd use .one() and do it like:
var details = '<p>Just some additional details</p>';
$('a').one('click',function () {
$('#services').append(details);
})
jsFiddle example
I'd strongly recommend you to follow a data attribute based approach for adding such kind of behavior. Otherwise you'll end up with a huge pile of spaghetti code. I recently prepared a small presentation about what I like to call data driven behavior.
Assuming that for your case it would also be fine to show / hide the details with a toggle button you could add such re-usable behavior with a few simple lines of code:
$('[data-toggle-show]').each(function() {
var $element = $(this),
$target = $($element.data('toggleShow'));
$target.hide();
$element.on('click', function() {
$target.toggle();
});
});
Then you can use this functionality anywhere in your markup using a data attribute:
<p>Welcome to the article. Do you want to read more?</p>
<button data-toggle-show="#article-more">read more</button>
<p id="article-more">Here you go! Some more to read...</p>
You can view the example on jsbin
Also, in my opinion, the correct HTML semantics for such behavior is to use a button instead of a link. I've also used a link in the past until I read an interesting debate on where to use a link and where to use a button. Actually the bottom line is that a link should be used where a user can right click to bookmark the URL and a button should be used where you could also decide to disable the possibility to execute the behavior.
Simply do:
<div id="services">SERVICES</div>
More Details
var details = '<p>Just some additional details</p>';
function moreDetails(obj){
obj.setAttribute("href", "")
$('#services').append(details);
}
Related
I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.
However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:
</textarea>
<script>alert("Hello World!");</script>
<textarea style="display: none;">
And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).
I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.
These few lines is what I use to live render HTML markup:
$(".main").on("keyup", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?
In order to sanitise your text area preview simply replace all the < and > with their html character code equivalents:
function showPreview()
{
var value = $('#writer').val().trim();
value = value.replace("<", "<");
value = value.replace(">", ">");
$('#preview').html(value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea id="writer" onInput="showPreview();">
</textarea>
<br/>
<hr/>
<div id="preview">
</div>
Edit: Actually, I think this solution is a little cleaner, and makes the below code unnecessary. In the velocity page all that is needed is to take advantage of the Spring framework. So I replace the textarea with this like so:
#springBindEscaped("myJavaObj.textAreaText" true)
<textarea id="actualTextArea" name="${status.expression}" class="myClass" rows="10" cols="120">$!status.value</textarea>
This paired with some backend Java validation and it ends up being a much cleaner solution.
But if you want a non-spring/ velocity solution, then this below works just fine
I cobbled together a quick fix as my main purpose is to eliminate the ability for others to execute scripts easily. It's not ideal, and I"m not claiming it to be the best answer, so if someone finds a better solution, please do share. I created a "sanitize" function like so:
function sanitize(text){
var sanitized = text.replace("<script>", "");
sanitized = sanitized.replace("</script>", "");
return sanitized;
}
Then the previous two event handlers now look like:
$(".main").on("keyup", "#actualTextArea", function () {
var textAreaMarkup = $('#actualTextArea').val();
var sanitizedMarkup = sanitize(textAreaMarkup );
$('#actualTextArea').val(sanitizedMarkup);
$('#previewTextArea').html(sanitizedMarkup);
});
// This one can remain unchanged and infact needs to be
// If it's the same as above it will wipe the text area
// on a highlight-backspace
$(".main").on("keydown", "#actualTextArea", function () {
$('#previewTextArea').html($('#actualTextArea').val());
});
Along with Java side sanitation to prevent anything harmful being stored in the DB, this serves my purpose, but I'm very open to a better solution if it exists.
I'm trying to make 2 plugins work together on a wordpress site. One is a sidepanel plugin that can be triggered by adding class="nks_cc_trigger_element"
to html <a href="..."> link coding.
The other plugin is an image mapping plugin that will only let me set the URL of a link, and I need the class attribute set to have it trigger the sidebar by clicking one of the mapped shapes of the image. The developers pointed me to the API with this code
$.imageMapProEventClickedShape = function(imageMapName, shapeID) {}
I have no experience with jQuery, and this seems like it should be a simple solution, but I'm lost. The relevant imageMapName and shapeID are simple enough to find, but I don't know how to simply open a link with jQuery or append that link with a class attribute.
Any help is appreciated!
http://jsbin.com/pirajo/6/edit?js,output
let a = document.querySelector("a");
if( a.classList.contains("hasClass") ){
a.addEventListener("click",function(e){
let link = this.getAttribute("href");
window.open(link,"_blank");
e.preventDefault();
});
}
I want to change all external links on my blog (blogspot here, that's why I'm looking for jQuery code) without changing the posting of my blog because I need a lot of work if I do that.
For example, my website is example.com.
I want to change all external links to
http://example.com/p/go.html?url=http://externallink.com
without need for any changes on my blog post. I don't have any idea to start with.
SOLVED: https://gist.github.com/2342509 Thanks everyone :D I just need to change it a bit.
In jQuery you can try:
// DOM ready
$(function(){
$('a[target="_blank"]').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
});
Ofcourse this will only work if you have set the target="_blank" property/attribute in HTML and if you want all links to open the same url. This idea derives from the fact you want to have external links open automatically in a different tab/window.
If this is not the required functionality, you can use a custom data- attribute in a similar way. Only difference is you will need to loop each link, and get the data from it.
// DOM ready
$(function(){
$('a[data-href]').each(function(){
var anc = $(this),
href = anc.prop('href'),
dataHref = anc.data('href');
anc.prop('href', href + '?url=' + dataHref);
});
});
HTML example:
external link
And now you will probably need to add more information if that is still not what you want.
Going off of #Tim Vermaelan's answer, you could try this, which will check for every link that doesn't start with your website's URL without relying on it being target="_blank":
$('a:not([href^="http://yoursite.com"])').prop('href', 'http://example.com/p/go.html?url=http://externallink.com');
In Private Logistics: Privacy-Sensitive Calendar, Todo, and Personal Information Management, data that is entered can be edited with a click, and there is support for either entering a link as <a href="... or entering a URL, which will be linkified.
This works great but it presents a problem when someone clicks on a link. The desired behavior is for the link to open and not to put the snippet of text into edit mode, which is the reverse of the usual pattern implemented by event.preventDefault()' or '...return false;}. (Clicks outside the link on the element should put the containing element in edit mode, same as a container that doesn't happen to have a link.)
How can I reverse the more common pattern using jQuery? My best guess now is to attempt introspection on the event target and see if it is an anchor. But that's just a best guess; I have seen plenty of examples of the pattern that would cancel the link loading another page but performing the added Ajax functionality of putting the container into edit mode; I'm not sure I've seen the reverse of that pattern which would follow the link and not put the container into edit mode.
I also see a way to dodge the matter by having links load in the same page, but that's the sort of solution I'd prefer to only adopt if there are intractable issues with implementation or the like.
Generally, you don't want to clean up your broad strokes, instead, don't make such broad strokes. Use an if statement prior to running e.preventDefault().
Something like:
var preventedLinks = $('a.preventthislink');
$('a').click(function(e){
if ($(this).index(preventedLinks) != -1) {
e.preventDefault();
}
});
you could alternatively just change the class of whatever you are preventing default on:
$(document).ready(function(){
$('.blue').removeClass('blue').addClass('green');
});
I have this HTML:
Track Your Package »
Somebody on this site was able to provide me with a script to prefix the URL with the domain http://www.example.com/ Here's the script:
$(document).ready(function(){
$('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick', $('a[onclick^="window.open(\'TrackPackage.asp"]').attr('onClick').replace("window.open('", "window.open('http://www.example.com/"));
});
However, I am having a little trouble with this:
The first issue is where there is multiple instances of the element. Here's a fiddle: http://jsfiddle.net/VMmZx/
Instead of one anchor being signed with ID=4 and the other with ID=5 as intended, they're both being signed with ID=4.
The idea is, each window.open function should be prefixed with http://www.example.com however, the remainder of the URL should remain intact...
The second problem I'm encountering is when the element does not exist on a page, the remainder of the jQuery fails...
Here's another fiddle: http://jsfiddle.net/VPf32/
The <a> should get the class foo, but since the element does not exist on the page, the jQuery does not execute.
Since the JavaScript is being included in the HTML template of the ASP.NET server, this can create many problems.
I hope I've been clear and you can help me. Thanks.
You can use .each() to iterate over each matching element and change them individually:
$('a[onclick^="window.open(\'TrackPackage.asp"]').each(function(index, element) {
element = $(element);
element.attr('onclick', element.attr('onclick').replace(/open\('/, 'open(\'http://www.example.com/'));
});
However, I don't think using links with a href of # and an onclick opening a window is as semantic as it could be. If possible, try changing the markup to this:
Track Your Package »
Now if someone is curious where it will lead them, the browser can show something useful in the status bar when you hover over it.
If you need to adjust the behavior further, add a class and bind for the click event. When they click, prevent the default action and open the window yourself, as you did before.
Why are you doing the click even inline like that? I would just output the links like:
Link Text
And then:
$('a[target=_blank]').click(function(){
var prefix = 'http://domain.com';
window.open(prefix + $(this).attr('href'));
});