Make each "li" from json it's own link? - php

Does anybody know how to make the text that appears in the following "li" both a link and also customizable through CSS? I have been unable to drop the text-decoration, change font style, color, etc. I've tried changing the style of the "tree" id but I was only able to change font size.
While both are important the link is crucial. Each "li" that is returned needs to be its own dynamically generated link. I've tried about 10 different ways now and I can't quite seem to get it to work.
<script>
function to_ul(id) {
var ul = document.createElement("ul");
for (var i=0, n=id.length; i<n; i++) {
var branch = id[i];
var li = document.createElement("li");
var text = document.createTextNode(branch.trackName);
li.appendChild(text);
ul.appendChild(li);
}
return ul;
}
function renderTree() {
var treeEl = document.getElementById("tree");
var treeObj = {"root":[{"id":"1","trackName":"Whippin Post"},{"id":"2","trackName":"Sweet Caroline"},{"id":"3","trackName":"Tears in Heaven"},{"id":"4","trackName":"Ain't She Sweet"},{"id":"5","trackName":"Octopus' Garden"},{"id":"6","trackName":"Teen Spirit"},{"id":"7","trackName":"Knockin on Heaven's Door"}]};
treeEl.appendChild(to_ul(treeObj.root));
}
</script>
</head>
<body onload="renderTree()">
<div id="tree"></div>
</body>
</html>
UPDATE
<script>
function to_ul(id) {
var ul = document.createElement("ul");
for (var i=0, n=id.length; i<n; i++) {
var branch = id[i];
var li = document.createElement("li");
li.innerHTML = "" + branch.trackName + ""
ul.appendChild(li);
function changeText(){
document.getElementById('player-digital-title').innerHTML = branch.trackFile;
}
}
return ul;
}
function renderTree() {
var treeEl = document.getElementById("player-handwriting-title");
var treeObj = {"root":[{"id":"1","trackName":"Whippin Post","trackFile":"test1.wma"},{"id":"2","trackName":"Sweet Caroline","trackFile":"test2.wma"},{"id":"3","trackName":"Tears in Heaven","trackFile":"test3.wma"},{"id":"4","trackName":"Ain't She Sweet","trackFile":"test4.wma"},{"id":"5","trackName":"Octopus' Garden","trackFile":"test5.wma"},{"id":"6","trackName":"Teen Spirit","trackFile":"test6.wma"},{"id":"7","trackName":"Knockin on Heaven's Door","trackFile":"test7.wma"}]};
treeEl.appendChild(to_ul(treeObj.root));
treeEl.appendChild(to_ul(treeObj.root));
}
</script>
</head>
<body>
Click here
<br/>
<br/>
<br/>
<br/>
<div id="player-digital-title"></div>
</body>
</html>

To make a "link" presumably you want an anchor element inside each li element, and for the a elements you'd want to have href attributes that you don't seem to have in your data. But by way of example, assuming you want to use the id as the href you could do this:
$(document).ready(function(){
var treeObj = {"root":[{"id":"1","trackName":"Whippin Post"},{"id":"2","trackName":"Sweet Caroline"},{"id":"3","trackName":"Tears in Heaven"},{"id":"4","trackName":"Ain't She Sweet"},{"id":"5","trackName":"Octopus' Garden"},{"id":"6","trackName":"Teen Spirit"},{"id":"7","trackName":"Knockin on Heaven's Door"}]};
var $ul = $("<ul></ul>");
$.each(treeObj.root,function(i,v) {
$ul.append($("<li></li>").append(
$("<a></a>").attr("href",v.id).html(v.trackName)));
});
$("#tree").append($ul);
});
Your question was tagged with "jQuery", so I've gone ahead and created the list (with anchors inside each li) using jQuery. The $.each() "loop" iterates through each element in the treeObj.root array, creating an a element with the id and trackName, appending that to a new li element, and appending that to a ul element. After the .each() finishes the new ul is appended to your tree div.
As far as styling the links, that's up to you to do the CSS you want, but since you mention dropping the text decoration you may want to start with something like this:
#tree a { text-decoration : none; }
Working demo: http://jsfiddle.net/B2Zsv/
(If that code and output as shown in the fiddle isn't the sort of thing you're looking for I suggest you update your question to show the desired output html that you want to generate.)
UPDATE
The following variation on my original code stores the track names as attributes on the anchors created, and then retrieves them on click.
$(document).ready(function(){
var treeObj = {"root":[{"id":"1","trackName":"Whippin Post","trackFile":"test1.wma"},{"id":"2","trackName":"Sweet Caroline","trackFile":"test2.wma"},{"id":"3","trackName":"Tears in Heaven","trackFile":"test3.wma"},{"id":"4","trackName":"Ain't She Sweet","trackFile":"test4.wma"},{"id":"5","trackName":"Octopus' Garden","trackFile":"test5.wma"},{"id":"6","trackName":"Teen Spirit","trackFile":"test6.wma"},{"id":"7","trackName":"Knockin on Heaven's Door","trackFile":"test7.wma"}]};
var $ul = $("<ul></ul>");
$.each(treeObj.root,function(i,v) {
$ul.append(
$("<li></li>").append( $("<a></a>").attr({
"href":v.id,"data-file":v.trackFile}).html(v.trackName) )
);
});
$("#tree").append($ul);
$("#tree a").click(function() {
var trackname = $(this).html(),
filename = $(this).attr("data-file");
// here add your code to do something with filename and/or trackname
return false;
});
});
As you can see my click handler doesn't actually do anything with the filename once it gets it (my updated demo http://jsfiddle.net/B2Zsv/3/ displays it), but that shows you how to get the right filename so from there you can figure out how to play it...

First off create the link in js:
function to_ul(id) {
var ul = document.createElement("ul");
for (var i=0, n=id.length; i<n; i++) {
var branch = id[i];
var li = document.createElement("li");
li.innerHTML = "<a href='wherever' class='listAnchor'>" + branch.trackName + "</a>"
ul.appendChild(li);
}
return ul;
}
and then style it in css:
<style>
.listAnchor {
text-decoration: none;
}
</style>

To create an a element within the li elements, simply apply the same techniques as demonstrated in the code as you have it:
function to_ul(id) {
var ul = document.createElement("ul");
for (var i = 0, n = id.length; i < n; i++) {
var branch = id[i];
var li = document.createElement("li"),
a = document.createElement('a'); // create the `a`
a.href = "http://example.com/"; // set the `href`
var text = document.createTextNode(branch.trackName);
a.appendChild(text); // append text to the a
li.appendChild(a); // append the a to the li
ul.appendChild(li);
}
return ul;
}
JS Fiddle demo.
To style that link, you can either use CSS in your document, or in an external stylesheet (as with any other CSS):
li a:link,
li a:visited {
/* style the link's 'default' state */
}
li a:hover,
li a:active,
li a:focus {
/* style the 'interactive' states of the links */
}
JS Fiddle demo.
You could, of course, simply apply the styles directly in the JavaScript that creates said elements, though this is needlessly expensive:
/* all the other stuff removed, for brevity */
var li = document.createElement("li"),
a = document.createElement('a'); // create the `a`
a.href = "http://example.com/"; // set the `href`
a.style.color = '#000';
a.style.textDecoration = 'none';
/* ...and other stuff... */
JS Fiddle demo.
This approach, apart from being expensive, also lacks the ability to style the :hover, :active, :visited and :focus styles.

Related

Highlight color on specific text in selection text option

Anyone idea how do I put a color highlight containing the word "stock" (check the image).
CSS, JavaScript, jQuery, or any language will do.
try this
<select>
<option>ARMAGEL HT 5MM ROLL(S) BLANKET TYPE(<span>STOCKS</span>:5 from)</option>
<option>ARMAGEL HT 5MM ROLL(S) BLANKET TYPE(<span>STOCKS</span>:5 from)</option>
<option>ARMAGEL HT 5MM ROLL(S) BLANKET TYPE(<span>STOCKS</span>:5 from)</option>
</select>
and css style with
select option span{
color: #ff0000;
}
You can use RegExp to find the desire word and wrap your word with a span tag using replaceWith.Apply class on span tag to give desire color.
var ChangeColor = 'Stocks';
var rgx = new RegExp('\\b(' + ChangeColor + ')\\b', 'ig');
$('div').contents().each(function() {
$(this).replaceWith($(this).text().replace(rgx, '<span class="red">$1</span>'));
});
.red {
color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
Some text(Stocks)
</div>
<div>
Some text( Stocks 1)
</div>
If you are using select2 then you can do it like below. You can highlight search text
CSS
<style>
.select2-rendered__match {
background-color: greenyellow;
}
</style>
JS
<script>
function markMatch(text, term) {
var regEx = new RegExp("(" + term + ")(?!([^<]+)?>)", "gi");
var output = text.replace(regEx, "<span class='select2-rendered__match'>$1</span>");
return output;
}
var query = {};
$('.js-data-example-ajax').select2({
allowClear: true,
minimumInputLength: 2,
escapeMarkup: function(markup) {
return markup;
},
language: {
searching: function(params) {
// Intercept the query as it is happening
query = params;
// Change this to be appropriate for your application
return 'Searching…';
}
},
templateResult: function(item) {
if (item.loading) {
return item.text;
term = query.term || '';
return markMatch(item.text, term);
},
}
});
</script>

How to add extra space to div using Jquery?

I am working on the sticky menu and highlight menu based on div id in WordPress. I have completed code well but I got a problem.
I have a sticky header when I click menu item in side sticky menu title going back to header title not visible.
I want result like this.'
How can I solve this?
My Jquery Code
jQuery(function($) {
/**
* This part causes smooth scrolling using scrollto.js
* We target all a tags inside the nav, and apply the scrollto.js to it.
*/
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, this.hash);
});
var aChildren = jQuery("#nav li").children(); // find the a children of the list items
var aArray = []; // create the empty aArray
for (var i=0; i < aChildren.length; i++) {
var aChild = aChildren[i];
var ahref = jQuery(aChild).attr('href');
console.log(ahref);
aArray.push(ahref);
} // this for loop fills the aArray with attribute href values
$(window).scroll(function(){
var windowPos = $(window).scrollTop()+70; // get the offset of the window from the top of page
console.log('Window Position:'+windowPos);
var windowHeight = $(window).height(); // get the height of the window
var docHeight = $(document).height();
for (var i=0; i < aArray.length; i++) {
var theID = aArray[i];
//console.log(theID);
var divPos = $(theID).offset().top-150; // get the offset of the div from the top of page
console.log('Div Position:'+divPos);
var divHeight = $(theID).height(); // get the height of the div in question
if (windowPos >= divPos && windowPos < (divPos + divHeight)) {
$("a[href='" + theID + "']").addClass("nav-active");
} else {
$("a[href='" + theID + "']").removeClass("nav-active");
}
}
if(windowPos + windowHeight == docHeight) {
if (!$("#nav li:last-child a").hasClass("nav-active")) {
var navActiveCurrent = $(".nav-active").attr("href");
$("a[href='" + navActiveCurrent + "']").removeClass("nav-active");
$("#nav li:last-child a").addClass("nav-active");
}
}
});
});
You need to offset the height of the heading when you jump to an anchored section.
Are you using the jQuery scrollTo plugin? If you can do something like:
$("#nav a").click(function(evn){
evn.preventDefault();
$('html,body').scrollTo(this.hash, 800, {offset: {top:-80, left:0} });
});
Options for scrollTo found here: http://demos.flesler.com/jquery/scrollTo/

Is there a way to add another list element at the end of the HTML list?

For example, in my test.html:
...
<div id="content">
...
<ul>
<li>url0</li>
<li>url1</li>
...
<li>url32</li>
<ul>
...
</div>
I want to add another list element ( <li>url33</li> ) at the end of the list from my add.php file.
I saw a similar post here, where a user was replacing the last list element. My thinking is that I would need to just add to the list length somehow then add to that length position... But I could be totally off in how I understand HTML lists (arrays?).
Pure JavaScript solution
var content = document.getElementById('content');
var ul = content.getElementsByTagName('ul')[0];
ul.innerHTML += '<li>url33</li>';
or
var content = document.getElementById('content');
var ul = content.getElementsByTagName('ul')[0];
var li = document.createElement('li');
li.innerHTML = 'url33';
ul.appendChild(li);
jQuery solution
$("#content ul").append('<li>url33</li>');
MooTools solution
var ul = $$('#content ul')[0];
ul.innerHTML += '<li>url33</li>';
YUI3 solution
YUI().use('node', function (Y) {
var ul = Y.one('#content ul');
ul.insert('<li>url33</li>');
});
Dojo solution
require([
'dojo/query',
'dojo/dom-construct'
], function (query, domConstruct) {
var content = query('#content ul')[0];
domConstruct.place('<li>url33</li>', content);
});
ReactJS solution
<script type="text/jsx">
/** #jsx React.DOM */
var content = document.getElementById('content');
var ul = content.getElementsByTagName('ul')[0];
React.render(
<li>url33</l1>,
ul
);
</script>
or
<script type="text/jsx">
/** #jsx React.DOM */
var content = document.getElementById('content');
var ul = content.getElementsByTagName('ul')[0];
React.render(
React.DOM.li(null, 'url33'),
ul
);
</script>
Using jQuery you can add element on end of the list
$("#content ul").append('<li>url33</li>');

JQUERY-PHP-MYSQL - Data from Mysql into a existing DIV list did not respond click event

Im a beginner in PHP, MYSQL, JQUERY.
I intended to load a photo gallery (ul) into a div.
The following snippet works well and the style applied to that element and its children works too.
The WHERE clause is enough to load 12 pictures with only one parameter (TabFotosVisivel=1).
Please check the following snippets out:
INDEX.PHP
<div id="idDivTC">
<ul>
$result = mysql_query("SELECT * FROM TabFotos WHERE TabFotosVisivel=1 ORDER BY TabFotosID DESC LIMIT 0,12");
while($row = mysql_fetch_array($result)){
$caminhoArquivo=$row["TabFotosCamArqMini"];
$descricao=$row["TabFotosDescricao"];
$titulo=$row["TabFotosTitulo"];
echo("<li><img class='claFotoMiniatura' src='".$caminhoArquivo."' title='".$titulo."' alt='".$descricao."'></li>");
}//fim do while
</ul>
</div><!-- /idDivTC -->
//-----------style of index.php------------------------
#idDivTC ul li {
display:inline;
}
#idDivTC ul li img{
margin:1px;
float:left;
}
Now I would like to load into the same structure another gallery and I use Jquery to call a page with pure PHP.
The additional parameter to WHERE clause id 'idLido'.
The code is
//------------- jquery of index.php----------------------
$(".claSubMenu").click(function (){
var idLido=$(this).attr("alt");
$.post("miniatura.php", { idLido:idLido})
.done(function(data) {
var arrayRetorno=new Array();
arrayRetorno=data.split("#");
for (i=0;i<arrayRetorno.length;i++){
$("#idDivTC ul").append(arrayRetorno[i]);
}
});
});
MINIATURA.PHP
<?php
require_once("bd.php");
$idLido=$_POST['idLido'];
$sentenca = "SELECT * FROM TabFotos WHERE TabFotosFKGalerias = ".$idLido." AND TabFotosVisivel=1";
$result = mysql_query($sentenca);
while ($row = mysql_fetch_array($result)){
$titulo=$row['TabFotosTitulo'];
$descricao=$row['TabFotosDescricao'];
$caminhoArquivo=$row['TabFotosCamArqMini'];
$retorno=$retorno."<li><img class='claFotoMiniatura' src='".$caminhoArquivo."' title='".$titulo."' alt='".$descricao."'></li>#";
}
echo $retorno;
mysql_close($con);
?>
After retrieve data, Jquery/javascript convert it into an array.
This is my point: I would like, as I said, to read each value of this array and append it to the that element/list, when I invoke
$(".claSubMenu").click(function (){
through
for (i=0;i<arrayRetorno.length;i++){
$("#idDivTC ul").append(arrayRetorno[i]);
}
It works, but the style doesnt applied anymore.
It seems to me that the former block is not the same the latter, although they have the same ID.
Besides, this click event
$("#idDivTC ul li > img").click(function (e){ ...
calls a JqueryUI dialog window, but It works only on the former structure as well.
How may I achieve my intent?
Thank you
In addition, this is the code to modal dialog window (Ui JQuery):
//--------------------modal of index.php ----------------
$("#idDivTC ul li > img").click(function (e){
e.preventDefault();
var titulo = $(this).attr("title");
var alternativa = $(this).attr("alt");
var imagemObj = new Image();
var caminhoArquivo=$(this).attr("src");
imagemObj.src= caminhoArquivo;
imagemObj.onload = function()
{
var largura=imagemObj.width;
var altura=imagemObj.height;
$(this).clone().dialog({
title: function (){
return titulo+" - "+caminhoArquivo;
},
modal: true,
resizable: false,
draggable: true,
width: function(){
return largura;
}
//fim da funcao da largura
});//fim da da this clone
};// fim da imagem load
});
//-----------------------------
For one, use event delegation to attach your click handlers: $("#idDivTC ul li > img").click(...) becomes $("#idDivTC ul").on("click", "img", ...).
The event isn't fired for the newly created elements because they don't have any click events bound to them.

Editing css with php or JQuery

Is there a way that I can change a css style sheet's data from a html form and php and/or JQuery. So if I have the following
widths.css
#main #section1 {
width: 25%;
}
#main #section2 {
width: 50%;
}
#main #section3 {
width: 25%;
}
So I want to have 3 text boxes S1, S2 and S3 and then a user can place values into each text box. It will check they add up to 100% or less and then it will write them to the css in place of 25%, 50% and 25%. How would I achieve this using php and/or JQuery.
Thanks
well there is a dirty but solution to this. use php to write javascript to the the html possibly after ending of body tag.
so the code goes like this
..
...
</body>
<?php echo <<< code
<script type="text/javascript">
document.getElementById("section1").style.width="$_POST['s1']";
// and then for each section u can do this
code;
?>
you will have to set the CSS dynamically on the page it self. Once the user entered the data, you can use little bit of AJAX to change the styles. So something like below would be your PHP and styles on the page. if you want this to be a permenant change make sure to put the settings in a DB against the user's profile. This can be added to your AJAX script as well.
<style type="text/css">
#main #section1 {
width: <?php echo $s1; ?>%;
}
#main #section2 {
width: <?php echo $s2; ?>%;
}
#main #section3 {
width: <?php echo $s3; ?>%;
}
</style>
HTH
You can use the jQuery addClass() to add a specific CSS class with the style you require.
To use PHP, you could use CSS internally on the page:
<style type="text/css">
<?php echo "width: 100px;" //for example ?>
</style>
But I wouldn't necessarily recommend that.
something basic but which should work
$(".validate").click(function(){
//I've assumed your text inputs were children of an element with id section$i
var w1 = Number($("#section1 input").val());
var w2 = Number($("#section2 input").val());
var w3 = Number($("#section3 input").val());
if(w1+w2+w3 == 100){
//here you change css rules for #section$i elements
$("#section1").css("width",w1+"%")
$("#section2").css("width",w2+"%")
$("#section3").css("width",w3+"%")
}
else{
alert("sum of values must equals 100%")
}
});
assuming that you have a clickable area with class validate
You can use this script i just made for you:
var merge = function(objectCollections){
var array = new Array();
foreach(objectCollections,function(objectCollection){
foreach(objectCollection,function(object){
array.push(object);
});
});
return array;
}
var foreach = function(object,loop){
for (var key in object) {
if (object.hasOwnProperty(key)) {
loop(object[key],key);
}
}
}
var changeCSS =function(value){
var links = document.getElementsByTagName('link');
var styles = document.getElementsByTagName('style');
var sheets = merge([links,styles]);
var rules = value.split(/[(\ *{)(\})]/g);
for(var i in sheets){
if(typeof sheets[i] == 'object'){
var sheet = sheets[i].sheet ? sheets[i].sheet : sheets[i].styleSheet;
for(var j in sheet.cssRules){
if(typeof sheet.cssRules[j].selectorText != 'undefined'){
if(sheet.cssRules[j].selectorText == rules[0]){
sheet.cssRules[j].cssText = value;
console.debug(sheet.cssRules[j].cssText);
}
}
}
}
}
}
usage example:
changeCSS('#main #section1 {width: 25%;}');
this will change the css (not set a style on a tag or something)

Categories