I'm working on a website for my custom themes on a blogging site. I want to have a review section, but I only want to have one review per page refresh. I was wondering if there is any way to write a script with jQuery or javascript (I'm not sure which one) to pick a random element from an array (All of the reviews will have a seperate element, each person having a different div ID with a different review) and display that element inside a div called #reviews, and hide the other elements? It sounds very confusing, but basically I need either jQuery or javascript to pick a review and put it in the review section. If anyone could help it'd be greatly appreciated.
Here's one way jsFiddle
<aside id="reviews">
<article class="review"></article>
<article class="review"></article>
<article class="review"></article>
</aside>
and
var $reviews = $('#reviews .review').hide();
$reviews.eq(Math.random()*$reviews.length).show();
But unless you plan on revealing the other reviews at some point (slider, or pagination), you should really do this server side. Sending people content just to hide it is a little wasteful.
jQuery is JavaScript. To get a random element from an array, use Math.random():
function getRandomElement(a) {
return a[Math.floor(Math.random() * a.length)];
}
I would use knockout.js which is great for binding JavaScript objects to DOM. You can fill an array of your object and data-bind it to the div. Each time you will bind a random element of the array to the div. The data binding is very simple:
<p>First name: <input data-bind="value: firstName" /></p>
// This is a simple *viewmodel* - JavaScript that defines the data and behavior of your UI
function AppViewModel() {
this.firstName = "Bert";
}
// Activates knockout.js
ko.applyBindings(new AppViewModel());
For more examples see the great tutorials in:
Knockout.js tutorials
Related
I have two hidden <div> elements which are hidden at the bottom of my page like so:
<div class="hidden-unit" style="display:none;">
<h1>ad unit one</h1>
</div>
<div class="hidden-unit" style="display:none;">
<h1>ad unit two</h1>
</div>
Further up my page I have another two div elements, like so...
<div class="visible-unit"></div>
<div class="visible-unit"></div>
I would like to loop through each of the hidden units, place the content from the first .hidden-unit into the first .visible-unit and then likewise for the second.
The content that sits within each .hidden-unit will actually be an inline script used for displaying ads, this is passed through from an array into a view that I have created in PHP so there is a strong possibility that more content could be added to the array or removed, so this loop needs to accommodate for such situations.
I have tried a number of solutions using jQuery's .each() but I can't seem to get it right. I've also created a JSFiddle should anyone want to demonstrate a solution:
https://jsfiddle.net/p89sq2df/3/
I've tried loads of different combinations and the latest attempt only seems to be populating the .visible-unit elements with the 'ad unit two' text.
$('.hidden-unit').each(function() {
$('.visible-unit').html($(this).html());
});
Anyone had to do anything like this before? I appreciate it's an odd one.
You can try using the index:
$('.hidden-unit').each(function(index) {
$('.visible-unit').eq(index).html($(this).html());
});
var visibleUnits = $('.visible-unit').toArray();
var x = 0;
$('.hidden-unit').each(function() {
visibleUnits[x].html($(this).html());
x++;
});
The gotcha is that there could be more .hidden-unit elements than .visible-unit elements, which would cause an exception. But this you put you on the right track.
You need to use the index the elements so you update matching instances. This can be done using each or html(function)
$('.visible-unit').html(function(index){
return $('.hidden-unit').eq(index).html();
});
Since you mention that the content is loaded by script originally, you may need to allow time for any asynchronous loading (if any) in the scripts
DEMO
Rather than trying to match indices and having to maintain two lists of divs, you can clone the hidden divs and add them to a container, or insert them before or after another element if you really don't want a container element.
$(".hidden-unit").clone()
.removeClass("hidden-unit")
.removeAttr("style")
.addClass("available-unit")
.appendTo(".container");
Working fiddle here: https://jsfiddle.net/ygn34zL8/
I would like to be able to allow a user to "filter" the contents of an HTML page from a drop down menu.
I have minimal coding skills but maintain a simple website produced using Emacs org-mode. (easy to assemble pages and produce different versions of the same content using tags.) The output is simple HTML.
I can easily produce different versions of a page and make them selectable with a drop down menu to move between them, but this means I have different versions of the same content on my website, which makes retrieval from search engines confusing.
Ideally, I would like user A to be able to select to see the whole page, user B to see some of it, and user C to see most of it except a small portion. This is a convenience to the users (not for security, etc.)
What is the simplest way of implementing this? I realize a web developer would probably use Ajax, etc., but that's not me.
Sounds like you could make use of showing/hiding sections of the page with some DIVs based on a drop down SELECT.
To do this, you wrap the content that you want to filter in some DIVs and create a JavaScript function that "filters" the displayed content based on the value attribute of the SELECT.
Here is a simple example:
HTML
<select id="myDropdown" onchange="filterContent();">
<option value="A">All content</option>
<option value="B">Some content</option>
<option value="C">Little content</option>
</select>
<div id="contentA">
** Content A ***
</div>
<div id="contentB">
** Content B ***
</div>
<div id="contentC">
** Content C ***
</div>
JavaScript
function filterContent() {
var user = document.getElementById("myDropdown").value;
var contentA = document.getElementById("contentA");
var contentB = document.getElementById("contentB");
var contentC = document.getElementById("contentC");
if(user=="A") {
contentA.style.display="block";
contentB.style.display="block";
contentC.style.display="block";
} else if (user=="B") {
contentA.style.display="none";
contentB.style.display="block";
contentC.style.display="block";
} else if (user=="C") {
contentA.style.display="none";
contentB.style.display="none";
contentC.style.display="block";
}
}
Try it here: http://jsfiddle.net/JsZ8S/
Here is another example with multiple different sections that can be shown or hidden based on the selection. Note that the scheme used for IDs is contentA1, contentA2, etc. the letter being the user and the number after the letter is the sequence since IDs must be unique. Also note the difference in the JavaScript code - because we have more sections, we have to account for showing and hiding them in the if/else block: http://jsfiddle.net/JsZ8S/2/
In case you are ready to use jQuery another example is using classes. If you find that you are creating numerous sections and are tired of keeping track of IDs, you might want to use classes. Classes in this case, work like IDs that you can use again and again. You mark any section you want displayed to all users (user A) with class="contentA", any area for users A and B with class="contentB" and everything else just leave unmarked. This is starting to get a bit un-simple at this point but see what you think.
Here is an example (requires jQuery) using classes: http://jsfiddle.net/JsZ8S/5/
You cannot do it with HTML alone. HTML defines a static document with static formatting. You need at least a little bit of JavaScript to dynamically change the page. Otherwise you have to create some sort of link or button that takes the browser to a new page with the desired changes. (This is about how the web worked for the first 5 or so years.)
A small about of JavaScript plus a library like jQuery should make this easy enough to do if you have any programming experience.
HTML is used to just creating the markup and CSS is used to style it. There is no way you can do "filtering" in plain HTML. You will definitely need some JavaScript knowledge. Try your hands on jQuery and angularJS. They are really easy to learn and the documentation is pretty amazing.
I am creating a UI, in which user can add / delete items (of similar layout).
It starts with one item and you can click 'add' to add more. The UI consists of several different types of items.
What I am doing currently is populating a single item item 1 ( of each type ) and on add event, I clone the item 1, replace the changes done by user in item 1 and append the clone to the container.
In simple words, instead of dynamically creating html with jQuery, I am cloning html of a div. But in this approach , I had to change a lot of things to keep to give the new item to initial state.
So, I want to avoid the replacing the edits done by user, so I was thinking something like below,
<script type="text/template" id="item_type1">
<div>
<div>Box</div>
</div>
</script>
<script type="text/template" id="item_type2">
<div>
<div>Box2</div>
</div>
</script>
And on add event, I want to do something like $('#item_type1').html() and $('#item_type2') to create new items.
I know there are sophisticated libraries like handlebar and mustache and underscore has its own way of implementing templates.
But I am not using any of these already and thus do not want to included them just to copy content. I dont want anything special. I am not passing variables. I am just cloning some markup to use again and again.
Is this way to insert html in script tags , going to work in all browsers ? and is it a good way ?
EDIT:
Its for the wp plugin and I assume js is turned on , else the plugin wont work anyways.
What about:
Your HTML should be, for example:
<script type="text/template" id="item_type1">
<div>
<h1>Box1</h1>
<p>
</p>
</div>
</script>
And your code would be:
var templateHtml = $('#item_type1').html();
var $item = $(templateHtml);
$('body').append($item);
$item.on('click', function() {});
This is an easy way that will work on all browsers.
Step 1: Create an HTML file with your template inside of it
Step 2: Using jQuery's load() method, call your HTML template into a div element in the main HTML file:
$("#main-div").load("yourtemplate.html")
Step 3: Be amazed
Is this a good idea? It depends:
If it's a self contained application on a known environment with a determined supported browser and with equally determined settings (like if JavaScript is on or not) then yea, sure. Why not?
If it's open to the public in every single browser possible with many different configurations, then no, it's a horrible idea. If your user doesn't have JavaScript enabled, then your content doesn't show up. Also, if one of your scripts break in production, then you are again left with no content. You can learn this lesson from when Gawker made this same mistake
I don't know anything about programming, so I'm trying to find out where to start learning + how difficult my problem is. Since I don't have any programming knowledge, I'll try to describe my problem in natural language, hope that is OK.
I have the html file of the penal code (a type of law). It contains many different rules, that are in numbered paragraphs (§ 1, § 4, etc).
Now I want to look at the source code and manually “tag” the paragraphs according to specific criteria. For example all the paragraphs that concern the use of a weapon get the “weapon” tag, or that have a minimum sentencing of 1 year and higher get a “crime” tag, etc.
At the end I want to view an interactive html file in Firefox/Chrome, where I could for example click on a “crime” button, and all §§§ that were tagged with “crime” would appear in bold red, keeping the rest of the document intact. Ideally I would also be able to click on “weapon” and would only see the §§§ tagged with “weapon”, making the rest of the document disappear.
The function it's just for me, so it would only need to work on a Xubuntu 11.04 desktop with Firefox or Chrome. The original source file would be http://bundesrecht.juris.de/stgb/BJNR001270871.html. The code looks strange to me, is there a way to convert it into something more easily manually editable?
Any help would be greatly appreciated. Primarily I don't know where to start learning. Do I need to know HTML, jQuery, or a programming language like Python? Do I need to set up an Apache server on my PC? Perhaps because of my ignorance of programming, this seems like a not too complex function. Am I mistaken in the belief that an amateur could build something like thins maybe one month?
I think this is not very difficult to make, although the tagging process can be quite labour-intensive.
You don't need much programming skills, especially when you want to tag stuff manually. You probably only need basic HTML and CSS and some Javascript to pull this off.
What I would do is the following
Create a local copy of the HTML file (use Save As in your browser)
Manually tag each § by giving it the appropriate tag as a classname
Create a list of all available tags and let javascript filter out the § you'd like to see
Now Step 1 is pretty easy I guess, so I'll go right to Step 2. The paragraphs in the HTML file are formatted according to a certain pattern, e.g.:
<div class="jnnorm" id="BJNR001270871BJNE009802307" title="Einzelnorm">
<div class="jnheader">
<a name="BJNR001270871BJNE009802307"/>Nichtamtliches Inhaltsverzeichnis
<h3><span class="jnenbez">§ 31</span> <span class="jnentitel">Rücktritt vom Versuch der Beteiligung</span></h3>
</div>
<div class="jnhtml">
<div>
<div class="jurAbsatz">
(1) Nach § 30 wird nicht bestraft, wer freiwillig etc.
</div>
</div>
</div>
</div>
What you want to do now is add your tag to the <div> element with the class jnnorm. So the above example would become (if the tag weapon would be appropriate):
<div class="jnnorm weapon" id="BJNR001270871BJNE009802307" title="Einzelnorm">
You do that for each paragraph in the HTML. This will be pretty boring, but okay.
Now Step 3. First create a list of links of all the tags you've just created. How you create lists in html is explained here. Put this at the top of the HTML document. What you want to do with javascript is when you click on one of the links in your list that only the paragraphs with the given class are shown. This is most easily done with jQuery's click event and the show and hide methods.
Updated with jQuery example
Make a menu like this
<ul id="menu">
<li id="weapon">Weapons</li>
<li id="crime">Crime</li>
</ul>
And then use the following jQuery
<script>
$(document).ready(function(){
// When a <li> element inside an <ul> with the id "menu" is clicked, do the following
$('ul#menu li').click(function(){
// Get the id of the <li> element and append a '.' so we get the right name for the tag (class) we want to show
var tag = '.' + $(this).attr('id');
// Hide all elements of class 'jnnorm'
$('.jnnorm').hide();
// Show all elements with the class name of tag we want
$(tag).show();
});
});
</script>
Note: HTML classes are denoted as .classname in jQuery whereas HTML id's are denoted as #idname.
Good luck!
This could be done using purely HTML/CSS and Javascript, so not server would be needed. JQuery would make the javascript side easier.
Basic idea of how to do it:
Use CSS style classes for your "tags"
Have a button for each tag with an onclick handler that uses JQuery to highlight everything with that tag (or make everything else invisible)
The HTML source code actually looks nicely structured, though it could use a few more linebreaks for sub-paragraphs. Any good HTML/XML editor has an autoformat feature that handles this, though you could get any specific format you want using a programming language with convenient text-manipulation facilities, such as Perl, awk or Python.
Maybe I've picked a totally inappropriate/bad example.
What I have is a user control that contains a bunch of dynamically created Telerik RadGrids.
My user control is added to a couple of Telerik RadPageViews that are part of a RadMultiPage that is used alongside a RadTabStrip.
What I need to do is call a Javascript function in my usercontrol to update it's display whenever it's parent RadPageView is selected.
So basically I have the following Javascript code:
function OnClientTabSelected(sender, args)
{
// Get the MyControl that is on this tab
var myControl = $find("whatever");
// Call a method that updates the display
myControl.doSomething();
}
Thanks,
David
You can add a wrapper div in your User Control and then extend that div using jQuery to add your desired methods and properties. The trick is to set the div's id='<%=this.ID%>' - that way the div has the same ID as the User Control (which is fine because the User Control doesn't actually render anything - only its contents).
Then back on your containing page, you can just reference your UserControl's ID using $get('whatever') - and you'll actually select your extended div.. which will have all your methods and properties on it.
The nice thing about this approach is that all of your methods and properties and neatly scoped and nothing is in the global namespace.
I have a full demo solution and details here if you want more info:
http://programmerramblings.blogspot.com/2011/07/clientside-api-for-aspnet-user-controls.html
Just make a call to javascript method in input button if you are sure about the name of that function.
<input type="button" value="test" onclick="doSomething()" />
If you place any javascript code in the control that will be spit on the page and it will be available for calling provided both of them are in the same form.
for example your code will look like this if you look into the source of that page.
<script type="text/javascript">
function doSomething()
{
alert(new Date());
}
</script>
<div>
<span id="MyControl1_Label1">Dummy label</span>
</div>
<hr />
<input type="button" value="test" onclick="doSomething()" />
Edit: This is not a good way to access these methods in my opinion. When you are putting some javascript code inside a control then it should be used in that control only (There is no rule as such, its just a design suggestion). If you are trying to access javascript code of a control from outside that control then you need to revisit your design.
If you can give us more details on why you want to access that method, may be we can suggest some better way to do that.
Update: (As you have modified your question): Bit tricky to answer this as I dont have hands on experience with Rad controls. I guess there should be some feature which will help you to update the controls in that page without using javascript, may be have a look at clientside-API provided for Rad.
May be somebody who knows about RAD controls will help you.
You should make the control method public
public void doSomething
and call this from the page
myControl1.doSomething();