I'm trying to setup some hyperlinks to set inline styles for various elements on a webpage. So far I have been able to store the element and attribute settings in hidden span elements and pass them to an alert dialog. However when I try to set these styles using the css function it is not working or throwing any errors.
HTML:
<a class="styleswitch">Boxed
<span class="elementselector" style="display:none">#page</span>
<span class="styleattributes" style="display:none">"width": "1000px"</span>
</a>
<a class="styleswitch">Wide
<span class="elementselector" style="display:none">#page</span>
<span class="styleattributes" style="display:none">"width": "100%"</span>
</a>
jQuery:
jQuery(document).ready(function(){
jQuery('a.styleswitch').click(function(){
var element_selector = jQuery(this).find("span.elementselector").contents().text(),
style_attributes = jQuery(this).find("span.styleattributes").contents().text();
// alert('Set ' + element_selector + ' to ' + style_attributes + '');
jQuery(element_selector).css( style_attributes );
return false;
});
You are passing a string to the .css() method, this means you are using it as a getter and not a setter.
I would suggest using HTML5 data-* attributes, here data-styles is a string representation of an object, by using jQuery .data() method you will have an object:
<a data-styles='{ "width": "1000px", "prop": "value" }'
data-selector="#page"
class="styleswitch">
Boxed
</a>
JavaScript:
$('a.styleswitch').on('click', function() {
var data = $(this).data();
$(data.selector).css(data.styles);
});
http://jsfiddle.net/7t4Jb/
Change jQuery(element_selector).css( style_attributes );
to ==> jQuery(element_selector).css( {style_attributes} );
and it should work.
There are 2 ways to implement css in jquery:
.css("width","px")
or
.css({"width":"px"})
What you were doing wrong was trying to implement css with the second way but with no {}.
Hope i helped you.
With this:
jQuery(element_selector).css( JSON.parse("{" + style_attributes + "}"));
Yes, it works.
Another option:
var styleParts = style_attributes.split(":");
jQuery(element_selector).css( styleParts[0].replace(/"/g, ''), styleParts[1]);
The replace is just to remove the double quotes from the style name.
However, in a future you may want to add more style rules (not just width), so I'd suggest you to add the brackets to the style rule (to become it JSON), so you'd have:
<span class="styleattributes" style="display:none">
{"width": "100%", "backgroundColor": "red"}
</span>
If you do this change, you'd read the style like this:
jQuery(element_selector).css( eval(style_attributes) );
(I'm using eval instead JSON.parse here because I assume you'll edit those css by hand and eval isn't as strict as JSON.parse).
Hope this helps. Cheers
Storing stuff like that in hidden <span> attributes is problematic because the browser still pays attention to the contents. A better (well, safer; some people don't like it for reasons I don't really understand) way to stash stuff like that is to use <script> tags with a non-JavaScript "type" attribute:
<a class="styleswitch">Boxed
<script type=text/my-selector class="elementselector">#page</script>
<script type=text/css-styles class="styleattributes">{ "width": "1000px" }</script>
</a>
The browser will completely ignore that (except for any embedded closing </script> tags). You can still fetch the contents from jQuery:
jQuery(document).ready(function(){
jQuery('a.styleswitch').click(function(){
var element_selector = jQuery(this).find(".elementselector").html(),
style_attributes = jQuery(this).find(".styleattributes").html());
// alert('Set ' + element_selector + ' to ' + style_attributes + '');
jQuery(element_selector).css( JSON.parse(style_attributes) );
return false;
});
Note that I modified the style attribute block to be a JSON structure, so that it can be parsed and turned into a JavaScript object in your "click" handler.
edit I don't know who the downvoters are, but this is a really common practice for doing things like storing HTML templates and JSON blocks. All browsers worth worrying about (including mobile browsers) completely ignore the contents of <script> blocks with non-JavaScript "type" attributes. That means that the contents can contain HTML fragments without causing any problems.
Related
I am making website where I am created a lot of labels that are assigned in output as here
Use fiddle link at the end of the post
<!-- lets say that I want to make a kind of board to show some game clans or... whatever -->
<label class='team' name='ally'>Madcowz</label><BR>
<label class='team' name='ally'>Fluffy Unicorns</label><BR>
<label class='team' name='enemy'>Blue bastards</label><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<!-- The problem is that the NAME tag does not exist for label in this case: -->
<!-- I can't use ID because ID should be unique values -->
<script>
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
document.getElementById('printSomeOutputHere').innerHTML += teams[i].name + ": " + teams[i].textContent;
document.getElementById('printSomeOutputHere').innerHTML += "<BR>";
}
</script>
Fiddle:
http://jsfiddle.net/cusnj74g/
name attribute is undefined, so how can I mark these labels with same name if I can't use (I can, but I should not) ID
A couple of points:
You seem to know that name is not a valid attribute for label elements. So don't use it, use data-name instead.
You're using label elements incorrectly. There are two ways you use label: A) By putting the input, select, or textarea it relates to inside it (<label><input type="checkbox"> No spam please</label>), or by using the for attribute to associate it with one of those elements elsewhere in the document (<label for="no-spam-please">No spam please</label>...<input id="no-spam-please" type="checkbox">). Having a label with no control in it and no for is fairly pointless; just use a span.
You're using jQuery in one place, but not in others. I suggest that if you're going to have a library on your page, it's best to get full use out of it. In this case, to access the attribute, you'd use $(teams[i]).attr("name") or better, $(teams[i]).attr("data-name") if you're using a data-* attribute (see #1 above). (Some may tell you to use .data to access the attribute; don't, that's not what it's for. But you might consider looking at what it's for and whether that helps you.)
.innerHTML += "content" is an anti-pattern. It makes the browser loop through all elements within the element you're doing it to to build a string, then append the string on the right with it, then parse the result, and delete all existing elements within the element and replace them with the parsed result. Instead, consider .insertAdjacentHTML("beforeend", "content")
You don't declare i anywhere, which means your code falls prey to The Horror of Implicit Globals. Declare i, or use any of several other ways to loop that don't require an index counter.
Your output will be fairly hard to read, recommend breaking it up (perhaps a div for each team?).
textContent is not reliable cross-browser, some browsers use innerText instead. (And there are differences in how whitespace is treated between them.) Since you're using jQuery, use text.
...but yes, the code would work if you used .getAttribute("name") rather than .name. Browsers make access to even invalid attributes available through getAttribute. They just don't necessarily create reflected properties for them.
Here's a version with the various comments above applied:
var output = $("#printSomeOutputHere");
$(".team").each(function() {
var $this = $(this);
output.append("<div>" + $this.attr("data-name") + ": " + $this.text() + "</div>");
});
<span class='team' data-name='ally'>Madcowz</span><BR>
<span class='team' data-name='ally'>Fluffy Unicorns</span><BR>
<span class='team' data-name='enemy'>Blue bastards</span><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
...or to avoid repeated appends we could use map and join:
$("#printSomeOutputHere").append(
$(".team").map(function() {
var $this = $(this);
return "<div>" + $this.attr("data-name") + ": " + $this.text() + "</div>";
}).get().join("")
);
<span class='team' data-name='ally'>Madcowz</span><BR>
<span class='team' data-name='ally'>Fluffy Unicorns</span><BR>
<span class='team' data-name='enemy'>Blue bastards</span><BR><BR>
<b>JS stuff:</b>
<div id='printSomeOutputHere'></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
From https://developer.mozilla.org/en-US/docs/Web/API/Element.name:
[The name property] only applies to the following elements: <a>, <applet>, <button>, <form>, <frame>, <iframe>, <img>, <input>, <map>, <meta>, <object>, <param>, <select>, and <textarea>.
Since you're using jQuery I would use something like:
for(var t in teams){
$('#printSomeOutputHere').get(0).innerHTML +=
teams[t].getAttribute("name")
+ ": "
+ teams[t].text()
+ "<BR />";
}
Use getAttribute instead:
teams[i].getAttribute('name')
Why not use multiple classes:
<label class='team ally'>Madcowz</label><BR>
<label class='team ally'>Fluffy Unicorns</label><BR>
<label class='team enemy'>Blue bastards</label><BR><BR>
And the JS:
<script>
var outEl = document.getElementById('printSomeOutputHere');
var teams = $(".team");
for(i=0; i<teams.length; i++)
{
outEl.innerHTML +=
(teams[i].hasClass('ally')? 'ally':'enemy') + ": " +
teams[i].textContent;
}
</script>
I've been building a list of links, all of which should change the content of a div to another specific content (about 4 lines of stuff: name, website, contact etc.) upon a click.
I found this code:
<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>
and used it in such a way:
<li class="pl11">
superlink')">Pomorskie</a>
</li>
And it doesn't work as I expected.
It changes hyperlinks text from 'Pomorskie' to 'superlink'.
The plain text works just fine but I need links.
here's the http://xn--pytyfundamentowe-jyc.pl/projektanci/kontakty-p/ (only two of them show anything)
But after trying all of your recomendations, I think I'd jump to different divs with #links, cause nothing worked with this :/
Thanks a lot for trying, and cheers :)
Just as a completely sideways look at this, I'd suggest avoiding the nesting weirdness / complexity, and reducing the problem down.
Setup the content in a hidden (ie. <div id="replacements">...</div>) Grab the innerHTML from the node you want, and be done with it.
Much easier to get replacement content from non-devs that way too, kinda works great if you're in a team.
// Probably better in a separate helpers.js file.
function replaceContentInContainer(target, source) {
document.getElementById(target).innerHTML = document.getElementById(source).innerHTML;
}
Control it with: (lose that href=javascript: and use onClick, better as an event handler, but for brevity I'll inline it as an onClick attribute here, and use a button.)
<button onClick="replaceContentInContainer('target', 'replace_target')">Replace it</button>
We have our target somewhere in the document.
<div id="target">My content will be replaced</div>
Then the replacement content sits hidden inside a replacements div.
<div id="replacements" style="display:none">
<span id="replace_target">superlink</span>
</div>
Here it is in JSBin
Improve the dynamic nature of this by using Handlebars or another nice JS templating library, but that's an exercise for the OP.
edit: Note, you should also name functions with a leading lowercase letter, and reserve the leading uppercase style for Class names e.g. var mySweetInstance = new MySpecialObject();
The quotes are mismatched! So when you click you are getting a JavaScript error.
The browser sees this string:
href="javascript:ReplaceContentInContainer('wojewodztwo', 'superlink')">Pomorskie<
as:
href="javascript:ReplaceContentInContainer('wojewodztwo', '<a href="
Chnage the " inside to #quot;
<li class="pl11">
Pomorskie
</li>
Example fiddle.
Also note, using the href tag for JavaScript is a BAD practice.
You've got a problem with nested quotes. Take a look in your DOM inspector to see what the HTML parser built from it! (in this demo, for example)
You either need to HTML-escape the quotes inside the attribute as " or ", or convert them to apostrophes and escape them inside the JS string with backslashes:
<a href="j[…]r('wojewodztwo', '<a href="http://address.com">superlink</a>')">…
<a href="j[…]r('wojewodztwo', '<a href=\'http://address.com\'>superlink</a>')">…
See working demos here and here.
Better, you should use a onclick attribute instead of a javascript-pseudo-url:
<a onclick="ReplaceContentInContainer('wojewodztwo', …)">Pomorskie</a>
or even a javascript-registered event handler:
<li class="pl11">
<a id="superlink">Pomorskie</a>
</li>
<script type="text/javascript">
function replaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
document.getElementBId("superlink").onclick = function(event) {
replaceContentInContainer('wojewodztwo', 'superlink');
event.prevenDefault();
};
</script>
(demo)
Essentially, I want to pull text within a div tag from a document on my server to place it in the current document. To explain the reason: I want to pull a headline from a "news article" to use it as the text for a link to that article.
For example, within the target HTML is the tag:
<div id='news-header'>Big Day in Wonderland</div>
So in my current document I want to use javascript to set the text within my anchor tags to that headline, i.e.:
<a href='index.php?link=to_page'>Big Day in Wonderland</a>
I'm having trouble figuring out how to access the non-current document in JS.
Thanks in advance for your help.
ADDED: Firefox style issue (see comment below).
I'm not sure where you're getting your HTML but, assuming you already have it in a string, you could create a document of your own, stuff your HTML into it, and then use the standard getElementById to pull out the piece you want. For example:
var doc = document.implementation.createDocument('http://www.w3.org/1999/xhtml', 'html', null);
doc.documentElement.innerHTML = '<body><div>Nonsense</div><div id="news-header">Big Day in Wonderland</div><p>pancakes</p></body>';
var h = doc.getElementById('news-header');
// And now use `h` like any other DOM object.
Live version: http://jsfiddle.net/ambiguous/ZZq2z/1/
Normally, I would try to solve an issue only with the tools specified by the user; but if you are using javascript, there really is no good reason not to just use jQuery.
<a id='mylink' href='url_of_new_article' linked_div='id_of_title'></a>
$(function() {
var a = $('#mylink');
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
That little function up there can help you update all your link's text dynamically. If you have more than one, you can just put it in a $('a').each() loop and call it a day.
update to support multiple links on condition:
$(function() {
$('a[linked_div]').each(function() {
var a = $(this);
a.load(a.attr('href') + ' #' + a.attr('linked_div'));
});
});
The selector makes sure that only the links with the existence of the attribute 'linked_div' will be processed.
You need to pull the content of the remote document into the current DOM, as QuentinUK mentioned. I'd recommend something like jQuery's .load() method
Can I completely rely upon jQuery's html() method behaving identical to innerHTML? Is there any difference between innerHTML and jQuery's html() method? If these methods both do the same, can I use jQuery's html() method in place of innerHTML?
My problem is: I am working on already designed pages, the pages contains tables and in JavaScript the innerHTML property is being used to populate them dynamically.
The application is working fine on Firefox but Internet Explorer fires an error: unknown runtime exception. I used jQuery's html() method and IE's error has disappeared. But I'm not sure it will work for all browsers and I'm not sure whether to replace all innerHTML properties with jQuery's html() method.
Thanks a lot.
To answer your question:
.html() will just call .innerHTML after doing some checks for nodeTypes and stuff. It also uses a try/catch block where it tries to use innerHTML first and if that fails, it'll fallback gracefully to jQuery's .empty() + append()
Specifically regarding "Can I rely completely upon jquery html() method that it'll perform like innerHTML" my answer is NO!
Run this in internet explorer 7 or 8 and you'll see.
jQuery produces bad HTML when setting HTML containing a <FORM> tag nested within a <P> tag where the beginning of the string is a newline!
There are several test cases here and the comments when run should be self explanatory enough. This is quite obscure, but not understanding what's going on is a little disconcerting. I'm going to file a bug report.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script>
$(function() {
// the following two blocks of HTML are identical except the P tag is outside the form in the first case
var html1 = "<p><form id='form1'><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></form></p>";
var html2 = "<form id='form1'><p><input type='text' name='field1' value='111' /><div class='foo' /><input type='text' name='field2' value='222' /></p></form>";
// <FORM> tag nested within <P>
RunTest("<FORM> tag nested within <P> tag", html1); // succeeds in Internet Explorer
RunTest("<FORM> tag nested within <P> tag with leading newline", "\n" + html1); // fails with added new line in Internet Explorer
// <P> tag nested within <HTML>
RunTest("<P> tag nested within <FORM> tag", html2); // succeeds in Internet Explorer
RunTest("<P> tag nested within <FORM> tag with leading newline", "\n" + html2); // succeeds in Internet Explorer even with \n
});
function RunTest(testName, html) {
// run with jQuery
$("#placeholder").html(html);
var jqueryDOM = $('#placeholder').html();
var jqueryFormSerialize = $("#placeholder form").serialize();
// run with innerHTML
$("#placeholder")[0].innerHTML = html;
var innerHTMLDOM = $('#placeholder').html();
var innerHTMLFormSerialize = $("#placeholder form").serialize();
var expectedSerializedValue = "field1=111&field2=222";
alert( 'TEST NAME: ' + testName + '\n\n' +
'The HTML :\n"' + html + '"\n\n' +
'looks like this in the DOM when assigned with jQuery.html() :\n"' + jqueryDOM + '"\n\n' +
'and looks like this in the DOM when assigned with innerHTML :\n"' + innerHTMLDOM + '"\n\n' +
'We expect the form to serialize with jQuery.serialize() to be "' + expectedSerializedValue + '"\n\n' +
'When using jQuery to initially set the DOM the serialized value is :\n"' + jqueryFormSerialize + '\n' +
'When using innerHTML to initially set the DOM the serialized value is :\n"' + innerHTMLFormSerialize + '\n\n' +
'jQuery test : ' + (jqueryFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED") + '\n' +
'InnerHTML test : ' + (innerHTMLFormSerialize == expectedSerializedValue ? "SUCCEEDED" : "FAILED")
);
}
</script>
</head>
<div id="placeholder">
This is #placeholder text will
</div>
</html>
If you're wondering about functionality, then jQuery's .html() performs the same intended functionality as .innerHTML, but it also performs checks for cross-browser compatibility.
For this reason, you can always use jQuery's .html() instead of .innerHTML where possible.
innerHTML is not standard and may not work in some browsers. I have used html() in all browsers with no problem.
Given the general support of .innerHTML these days, the only effective difference now is that .html() will execute code in any <script> tags if there are any in the html you give it. .innerHTML, under HTML5, will not.
From the jQuery docs:
By design, any jQuery constructor or method that accepts an HTML string — jQuery(), .append(), .after(), etc. — can potentially execute code. This can occur by injection of script tags or use of HTML attributes that execute code (for example, <img onload="">). Do not use these methods to insert strings obtained from untrusted sources such as URL query parameters, cookies, or form inputs. Doing so can introduce cross-site-scripting (XSS) vulnerabilities. Remove or escape any user input before adding content to the document.
Note: both .innerHTML and .html() can execute js other ways (e.g the onerror attribute).
"This method uses the browser's innerHTML property." - jQuery API
http://api.jquery.com/html/
Here is some code to get you started. You can modify the behavior of .innerHTML -- you could even create your own complete .innerHTML shim. (P.S.: redefining .innerHTML will also work in Firefox, but not Chrome -- they're working on it.)
if (/(msie|trident)/i.test(navigator.userAgent)) {
var innerhtml_get = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").get
var innerhtml_set = Object.getOwnPropertyDescriptor(HTMLElement.prototype, "innerHTML").set
Object.defineProperty(HTMLElement.prototype, "innerHTML", {
get: function () {return innerhtml_get.call (this)},
set: function(new_html) {
var childNodes = this.childNodes
for (var curlen = childNodes.length, i = curlen; i > 0; i--) {
this.removeChild (childNodes[0])
}
innerhtml_set.call (this, new_html)
}
})
}
var mydiv = document.createElement ('div')
mydiv.innerHTML = "test"
document.body.appendChild (mydiv)
document.body.innerHTML = ""
console.log (mydiv.innerHTML)
http://jsfiddle.net/DLLbc/9/
Ok basically I have this javascript file http://assets.revback.com/scripts/share1.js that basically adds a bunch of share buttons via javascript.
What I want to do, is change the twitter image link to use an url shortener:
so instead of:
<a href=\"http:\/\/twitter.com\/home?status=Interesting Post:(UURRLL)\" title=\"Click to share this page on Twitter\"><img src=\"http:\/\/assets.revback.com\/scripts\/images\/twitter.png\" border=\"0\"\/><\/a>
I want to use
<a href="#" onClick="window.location='http://ko.ly?action=shorten&uri=' + window.location + '&dest=twitter.com/?status=Reading ';"><img src=http://assets.revback.com/scripts/images/twitter.png"><\/a>
but I need that bottom one, to be written with javascript friendly syntax. i.e. like in the top one, instead of http://, you have http://
Lose the onclick. There is no benefit to it whatsoever, since it just acts like a normal link (except much more broken). Now you don't have to worry about escaping JavaScript inside JavaScript and the consequent \\\\\\\\ madness.
var buttonhtml= (
'<a href="http://ko.ly?action=shorten&uri='+encodeURIComponent(location.href)+'&dest=twitter.com/?status=Reading">'+
'<img src=http://assets.revback.com/scripts/images/twitter.png">'+
'</a>'
);
(Note that the encodeURIComponent, which is essential to correctly inserting your current URL into another URL without breaking, is also protecting you from HTML-injection, since < and & characters get %-encoded. Without that safeguard, any page that includes your script has cross-site-scripting vulnerabilities.)
Better still, lose the HTML string-slinging altogether and use DOM methods to create your content. Then you don't need to worry about & and other HTML escapes, and you don't have to hack your HTML together with crude, unreliable string replacing. You seem to be using jQuery, so:
var link= $('<a>', {href:'http://ko.ly?action=shorten&uri='+encodeURIComponent(location.href)+'&dest=twitter.com/?status=Reading'});
link.append('<img>', {src: 'http://assets.revback.com/scripts/images/twitter.png'});
link.appendTo(mydiv);
ETA: I'd replace the whole markuppy mess with a loop and the data broken out into a lookup. ie. something like:
(function() {
var u= encodeURIComponent(location.href);
var t= encodeURIComponent(document.title);
var services= {
Facebook: 'http://www.facebook.com/sharer.php?u='+u,
Twitter: 'http://ko.ly?action=shorten&uri='+u+'&dest=twitter.com/?status=Reading',
StumbleUpon: 'http://www.stumbleupon.com\/submit?url='+u+'&title='+t,
// several more
};
var share= $('<div class="ea_share"><h4>Share this with others!</h4></div>');
for (var s in services) {
share.append($('<a>').attr('href', services[s]).attr('title', 'Click to share this on '+s).append(
$('<img>').attr('src', 'http://assets.styleguidence.com/scripts/images/'+s.toLowerCase()+'.png')
));
}
$('#question .vt').append(share);
})();
Try this
<a href="#" onClick="window.location='http://site.com?action=shorten&uri='+
window.location + '&dest=twitter.com/?status=Reading;'">tweet this</a>
<a href="#" onClick="window.location='http://site.com?action=shorten&uri=' + window.location.href + '&dest=twitter.com/?status=Reading ';return false;">tweet this
Change the href of the link in the onclick attribute:
tweet this
The default action (going to the page designated by the href attribute) will always still be executed unless the event handler onclick receives a return value of false. So, changing the href before it happens will cause it to go to the page you want it to as long as you don't return false.