So ive sort of conjured up a make shift way to do site properties, but am wondering if there is a way to improve my method. The objective is to have 1 html file where my client will be able to use a cms tool and update common values on the site such as repeated headers, thank you messages, company name, etc. I would like to use Javascript to accomplish this.
var spSelectResultsTxt = $("#sp .selectResultsTxt");
$(".main-content .selectResultsTxt").text(spSelectResultsTxt.text());
Heres an active fiddle, http://jsfiddle.net/trobbins26/VwtWD/4/
The script passes a text value from one div (which the client will update in a cms) to a class on some page in the site. The only problem is I don't want to create a var for every property that may exist on the site.
Is there a way in my script to say [if the #sp .class matches the .main-content .class, apply the text within the #sp .class as the text within the .main-content .class? Essentially creating one rule that can apply to every property i create.
Any feedback would be helpful.
Something like this should do what you want. It will loop through all elements with classes, in order. If an element has multiple classes, it will match elements that have all the same classes. It doesn't filter duplicates, so if an element is matched multiple times, the last match overwrites any previous matches.
EDIT: Here's a demo: http://jsfiddle.net/VwtWD/6/
This will do the trick:
HTML:
Javascript:
Updated Fiddle here: http://jsfiddle.net/VwtWD/7/
Explanation:
You just loop through the child elements of
div.sp
, then access its class and text and go looking for a matching element on the page to update.I've made some improvements:
It's best to leave classes for identifying the target elements, and use the data- binding on the elements that store the user-entered text. It's easily accessible through the jQuery
.data()
function as in my solution above.It'd probably also be nice to be able to specify the full CSS path for each element, so you can scale the solution to more complex pages.
Personally I'd also use the
.html()
method to set html, not just text, in case the client wants to use a<br>
tag or<em>
or<img>
, etc. Example:Other feedback:
Is there a reason you're using client-side javascript to achieve this? You could do it on the server-side pretty easily (even in javascript with node.js) which would have a number of benefits, including - Google etc. won't see the content which is an issue for SEO - Browsers without javascript won't see the content (admittedly this is a very small number and so may not be a concern, but worth pointing out)
Regardless, as a quick-hack-solution, it works.