HTML document pagination without jQuery - javascript

I have a large page having a lot of divs and all these divs are enclosed in a single div. And I have number links on the top of the page equal to the total enclosed divs I have. Now what I want to do is, on click on a number, I want to show only div corresponding to that number and hide all other.
links--> 1 2 3 4 5 6 7 .....
<div id="all">
<div id="mail1">..........</div>
<div id="mail2">..........</div>
<div id="mail3">..........</div>
<div id="mail4">..........</div>
<div id="mail5">..........</div>
<div id="mail6">..........</div>
.....and so on
</div>
I have to do it inside an HTML and that HTML will be stored and may be viewed offline as well, so cannot use jQuery here. Have to do it using JavaScript itself.
Could anybody help me with the JavaScript code here?.

<script type="text/javascript">
var divIds = ["mail1", "mail2", ..., "mailn"];
function showDiv(showId) {
for(var i = divIds.length; i--; ) {
if(divIds[i] === showId)
document.getElementById(showId).style.display = "block";
else
document.getElementById(divIds[i]).style.display = "none";
}
}
</script>
Then your links at the top will look like this:
1
Haven't tested it, but that's the idea. Downsides are you have to maintain the div in 3 places in code
In the var divIds array.
In the html tag itself.
In the links across the top.
You could write some javascript to generate all 3, taking away the maitenance part of it entirely.
As for using jQuery in an offline doc, the best route would probably be to include the text of the jquery.min.js file in the doc itself inside of <script></script> tags. That way you don't have to worry about paths and what-not.

You may do something like that (don't judge me on js coding style, i'm not a js ninja):
window.onload = function() {
var outer = document.getElementById("all");
for (var i=0; i < outer.childNodes.length; i++) {
outer.childNodes[i].addEventListener("click", doSomething);
}
function doSomething() {
// here you can run loop for changing display style for you divs
console.log(this.id);
}
}

I made an unobtrusive example without knowing the div ids:
http://jsfiddle.net/8pQzx/2/
Its more code but this is what you get if you dont want to use a js lib. ;)

Related

If URL contains this string then hide all divs with this class/id (loop script)

I am trying to hide some divs when url contains an specific string.
For example, i have this code that hides the first div:
<div id="ficha">Hello</div>
<div id="ficha">world</div>
<div id="ficha">...</div>
<script>
if (/info|mapo/.test(window.location.href)) {
document.getElementById('ficha').style.display = 'none';
}
</script>
URLs:
www.example.com/all ------> Not hide the div
www.example.com/info-----> Hide the div
www.example.com/mapo---> Hide the div
The first problem with the script is that it only hides the first div saying Hello, but i want to hide all the divs. So, i think it's necessary to do a loop... ¿how can i do that?
The second thing is running two different scripts to hide different divs according the url string content.
Maybe this can be achived by making an else function. Always the loop its necessary and even better if it's executed after load page.
For example:
<div id="ficha">Hello</div>
<div id="ficha">Hello2</div>
<div id="ficha2">world</div>
<div id="ficha2">...</div>
<!-- First script hides divs with id="ficha" if url string has "info" or "mapo" -->
<script>
if (/info|mapo/.test(window.location.href)) {
document.getElementById('ficha').style.display = 'none';
}
</script>
<!-- Second script hides divs with id="ficha2" if url string has "all" -->
<script>
if (/all/.test(window.location.href)) {
document.getElementById('ficha2').style.display = 'none';
}
</script>
The code will be execute in Database Activity of Moodle.
Thanks in advance.
This script will help you.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
window.onload = function () { //The function to execute when the page is loaded
var string_contain = ''; //Set this as your string
var url = window.location.href;
if(url.indexOf(string_contain) >= 0) { //If url contains then...
var x = document.getElementsByClassName("your_class"); //Create an array that contains your divs with your_class class
for(var a = 0;a<x.length;a++) { //Do some stuff for each value of the array
x[a].style.display = 'none';
}
}
}
</script>
</head>
<body>
<div class="your_class"></div>
</body>
</html>
Remeber that the ID is associated with just one element, so it won't work if you're trying to access more than one element.
You've got a few issues here:
First, like user adeneo mentioned in their comment, you cannot share IDs. Classes, however, can be shared so you probably want your <div> elements to say class="ficha".
Second, you want to hide or show divs based off of a string in the URL, but your URLs are composed of unique paths. You're trying to hide divs, when you should just be building the pages differently. Unless there's more information you need to add about this.
www.example.com/mapo is, at least in the representation you've provided, a different HTML page from www.example.com/info so why not build them as separate pages rather than going through unnecessary logic to show and hide <div> elements?
The third issue: you don't want a for loop so much as a for-each loop. This first question will give you direction on how to select all elements with the specified class:
JavaScript get elements by class name and tag name
Then using the array you've selected from the above information, you can use Javascript Documentation for using forEach on arrays to change your elements' visibility.
Since its not unique, a CSS class would be more appropriate. Something like this should work:
function hideItemsByClass(className){
var matchedItems = document.getElementsByClassName(className);
for(var i = 0; i < matchedItems.length; i++){
matchedItems[i].style.display = 'none';
}
}

Using regexes to modify the text of html (with javascript)

I want to modify the text in a html file using javascript in an android webview.
Essentially, I want to do what android Linkify does to text, but I don't want to do it with java code, because I feel like that might delay the webview rendering the html (if I parse the text before sending it to the webview).
So, for example a piece of html like this:
<html>
<body>
google.com <!--these two shouldn't be linked-->
akhilcherian#gmail.com <!--these two shouldn't be linked-->
<p>www.google.com</p> <!--this should be linked-->
<p>102-232-2312 2032-122-332 </p><!-- should be linked as numbers-->
</body>
</html>
Should become this:
<html>
<body>
google.com
akhilcherian#gmail.com
<p>www.google.com</p>
<p>102-232-2312 <a href="tel:2032-122-332>2032-122-332</a> </p>
</body>
</html>
I already have the regexes to convert numbers and email ids to links, and they're working well enough. What I want to ensure is that I don't link anything that's already within tags. I've removed anchor tags, so they're not an issue, but I also need to avoid linking things like this:
<div width="1000"> <!-- Don't want this '1000' to be linked (but I do want other 4 digit numbers to be)-->
So for example if my regex for links is:
var replacePattern1 = /((https?|ftp|file):\/\/[-A-Z0-9+&##\/%?=~_|!:,.;]*[-A-Z0-9+&##\/%=~_|])/gim
How do I make sure that it's not within < and >? (Answers using javascript would be appreciated, but if you feel like this is a stupid way of doing it, please let me know about alternatives).
If you're answering with javascript, this question can essentially be shortened to:
How do I write a regex in javascript to search for patterns which are not surrounded by '<' '>' tags
So if you use JS than mean is client side, your DOM page have free access of all objects of your page coef events.
May be in this step you dont need to use a regex just using DOM.
jquery lib can easy update DOM object.
in your step you want only tag.
So i suggest :
//using jquery
$("p").each(function(){
console.log($(this))
});
//js
var paras = document.getElementsByTagName("p");
for(p in paras){
console.log(paras[p])
}
As i tell you the deal is manipulate the DOM so example with you step dunno if exactly what you try to get :
var paras = document.getElementsByTagName("p");
var hrefs = [];
//what you want to replace in the loop of p
var json_urls = {"links":["http://", "tel:"]};
for(p in paras){
//copy of text content of your p
var text_cp = paras[p].textContent;
//delete the p[i] content
paras[p].textContent = "";
//create element dom a
hrefs[p] = document.createElement("a");
//i add attribute id with some affectation unique
hrefs[p].id = "_" + p;
//add attribute href to a with some affectation replace + content
hrefs[p].href = json_urls.links[p] + text_cp;
hrefs[p].textContent = text_cp;
paras[p].appendChild(hrefs[p]);
}

Run same javascript independent from each other

Working on the following demo, I have got a problem about making the code work twice (or more times).
I just wanted to add more "before/after" images, but seems like the draggable bar only works on the main one, and applies the movement to the others.
Is there any solution to make it work independent from each one?
Where could be the error:
$(function(){
var $dragMe = $("#dragme");
var $beforeAfter = $("#before-after");
var $viewAfter = $(".view-after");
Draggable.create($dragMe, {
type:"left",
bounds: $beforeAfter,
onDrag:updateImages
});
DEMO: JSFIDDLE
As answered on my previous post by #Jonas Grumman, here goes the solution:
JSFIDDLE
The main problem was on executing two ID tags on the same html page.
Otherwhise was my mistake since I forgot to change it on css, so focusing only on html & javascript was an error.
So modifying the following parts, was enough:
HTML (before):
<div id="dragme"></div>
HTML (after):
<div class="dragme"></div>
Javascript (before):
var $dragMe = $("#dragme");
Javascript (after):
var $dragMe = $(".dragme");
CSS (before):
#dragme{
some css styles here
}
CSS (after):
.dragme{
some css styles here
}

JSF Set CSS Style Using Javascript?

I have been looking with no success to see if I can dynamically apply a css style to JSF component or div using javascript. Is this possible.
This is pseudo code
<div style="myJSStyleFunction("#{myBean.value}")"> stuff </div>
And the function would return something like "position:relative;left:25px;"
I've had no luck and maybe it can't be done but would like a second opinion.
Edit:
I'm trying to see if I can keep a separation / reduce the coupling between the presentation/view and the model/controller. This is for indenting commenting or product reviews (to nest replies to comments or reviews). The most I really want to track is an integer on how deep a reply is. First level = 0 second level = 1, and so on. So a comment or product review would be 0 deep, a reply to the comment or review would be 1 and so on.
Then in the EL I wanted to call a javascript function and do something like
<script>
myJSStyleFunction(depth){
if(depth<=5){
var nest=20*depth;
var style="position:relative;left:" + nest + "px;";
return style;
}
}
</script>
And then then say for a third level comment (a reply to a reply) it would look like this:
<div style="position:relative;left:40px;"> stuff </div>
where
#{myBean.value}
evaluates to 2
I suspect like Daniel says I'll have to tightly couple the view but I'd rather not have to. I'd think there has to be a way. But maybe not.
I don't know where there are cleaner solutions for this. However this is one suggestion.
Assume your page looks like below and myBean.getValue() method returns an integer.
<h:form id="frm">
<div style="#{myBean.value}"> div1 </div>
<div style="#{myBean.value}"> div2 </div>
</h:form>
So you can do something like this at 'window.onload'.
<head>
<script>
window.onload = function() {
var childList = document.forms['frm'].childNodes;
for(var i = 0; i < childList.length; i++) {
if(childList[i].nodeName == 'DIV') {
var _div = childList[i];
var depth = _div.getAttribute('style');
_div.setAttribute('style', 'position:relative;left:' +(depth *20)+ 'px;');
}
}
}
</script>
</head>
Note: 1. In above sample code I assume all the DIVs inside the form should be indented.
2. For IE you may need to use _div.style.setAttribute('cssText','position:relative;left:' +(depth *20)+ 'px;')
3. Another solution for your question is using <script> tags immediately after your divs and putting the js part inside them. In this way you don't have to use fake styling style="#{myBean.value}" or window.onload event because you can directly call #{myBean.value} in your script.
I decided to skip the javascript approach and settled on a simpler and I think cleaner method to create the dynamic css classes for my situation. I already capture/calculate the depth value for each comment when it is entered. So I am just returning that value in EL and concatenating it to a 'base name' for the css class like so:
<div class="indent_#{(comment.commentDepth le 5) ? comment.commentDepth : 5}" >
comment comment blah blah blah
</div>
"indent_" is the base name for the css class. So for a 0 level comment it will have a class="indent_0". A reply to that comment will have class="indent_1".
I use the ternary so that if there are lot of replies under a given comment it doesn't indent right off the right hand side of the page. Even though you can keep going deeper, it will only indent up to 5 levels.
For my case at the moment, this is a simpler and cleaner method of adding some dynamically generated css class names. Right now I have to define 6 classes for this in the css file, but perhaps I'll figure out how to nest the boxes but it isn't a priority this works just fine for me for now.

How to create an effect higher up in the view than the logic that determines it?

I have a simple if statement in my view that returns x = 0 or 1. Based on this simple result, I want to change the styling of the div that contains the entire section.
<div>
conditional that returns x=1 vs x=0 (and a few displayed items)
based on this loop, restyle the div
</div>
Let's say, if x = 1, I want to make background-color:rgb(210,215,220);
How can I accomplish this? I am not experienced with Javascript but I'm sure any code required would be very simple. Thank you!
Add an ID to your DIV like:
<div ID="colorThis">
conditional that returns x=1 vs x=0 (and a few displayed items)
based on this loop, restyle the div
</div>
Then do this:
if(x==1)
{
​document.getElement​ById('colorThis').style.background = 'rgb(210,215,220)'​​​​;​​​​​​​​​​​​​​
}
<script>
if(x==1)
{
$("#divid").css("background-color","rgb(210,215,220)");
}
</script>
Include jQuery, and give the div's id to divid

Categories

Resources