I want to create separate backgrounds for each letter in the site-description span within the header on the Wordpress responsive theme.
I have added a function in functions.php
<?php
/**
* Setup Responsive Child Theme Functions
*/
function site_description_spans() {
echo 'Text within header'; // Replace this line with code from `https://stackoverflow.com/questions/17517816/color-every-character-differently
}
add_action( 'responsive_in_header', 'site_description_spans' );
?>
This successfully targets within the header within the responsive theme
But then I tried to add the following code within this function from another Stack Exchange post by replacing the
echo 'text within header' //above
The link to the javascript function on stack exchange is here
Color every character differently
and the relevant code is
$('.site-description').find('span').each(function(){
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for(var i=0; i<len; i++){
var bgColor= '#'+ (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:'+bgColor+'">'+ text.charAt(i) +'</span>';
}
$el.html(newCont);
});
And it doesn't seem to work. Would be grateful for any suggestions.
Now i'm not too sure on the outputted HTML but i'm going to take a wild guess, that this is how the HTML is being output:
<span class="site-description">
Text within header
</span>
What you need if the code is to work as expected
<div class="site-description">
<span>
Text within header
</span>
</div>
Option 1 - Change HTML
Change your HTML code so that a span is contained within a div and the function to add the text is within the span
Something like this
<div class="site-description">
<span>
<!-- RUN FUNCTION HERE -->
</span>
</div>
Option 2 - Change jQuery
Change your jQuery function to something like this:
$('.site-description').each(function() {
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for (var i = 0; i < len; i++) {
var bgColor = '#' + (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:' + bgColor + '">' + text.charAt(i) + '</span>';
}
$el.html(newCont);
});
Or generally just fix the first part of the query so that it finds the correct class or element.
Ok,
I have tried option 2 and just inserted it in the original function but I am not really sure what I am doing here. I understand what you suggested in option 2 and it looks like that would work, I am just not sure how to add it as a function in functions.php
This is what I have
function site_description_spans() {
$('.site-description').each(function() {
var $el = $(this),
text = $el.text(),
len = text.length,
newCont = '';
for (var i = 0; i < len; i++) {
var bgColor = '#' + (Math.random() * 0xffffff).toString(16).substr(-6);
newCont += '<span style="background:' + bgColor + '">' + text.charAt(i) + '</span>';
}
$el.html(newCont);
});
}
add_action( 'responsive_in_header', 'site_description_spans' );
?>
Trouble is that I get the following error with it
Parse error: syntax error, unexpected '(', expecting T_VARIABLE or '$' in /***/*****/public_html/*****/dev/wp-content/themes/responsive_child/functions.php on line 11
Related
I want to run a for loop that will produce a new div (with class 'container') containing a single link. E.g. the first div will show 'link6.php', the second div will show 'link5.php' etc. However, currently it seems that the loop is running out the full loop in each div (I have attached a picture showing this).
for (var i = 6; i > 0; i--) {
$('#everything').append('<div class="container"></div>');
var link = "link" + i + ".php" + "<br />";
$('.container').append(link);
}
Thank you very much in advance. I am new at this and your help is much appreciated ;)
The problem is that after you append the div, you select all .container elements and append the text to each. There seems to be no reason why you couldn't do the following.
for (var i = 6; i > 0; i--) {
$('#everything').append('<div class="container">link'+i+'.php<br /></div>');
}
This is my recommendation for your code. I recommend you to cache things first, and understand how jQuery's DOM selection works.
var everythingCached = $('#everything');
var container = $('<div class="container"></div>');
for (var i = 6; i >0; i--) {
var cached = everythingCached.append(container);
var link = "link" + i + ".php" + "<br />";
cached.append(link);
}
https://jsfiddle.net/47g4f14p/
When you do $(".container").append(), it appends to every DIV with class="container", not only the one you just appended in this loop.\
The simple way to fix this is to include link in what you append to #everything.
for (var i = 6; i > 0; i--) {
var link = "link" + i + ".php" + "<br />";
$('#everything').append('<div class="container">' + link + '</div>');
}
Or you could create the container as an object:
$('#everything').append($('<div>', {
"class": "container",
html: "link" + i + ".php<br/>"
});
or you could assign the container to a variable and append to it:
var container = $('<div class="container">').appendTo("#everything");
var link = "link" + i + ".php" + "<br />";
container.append(link);
The problem is because everytime you do $('.container').append(link);, the $('.container') gathers all existing divs including the ones added in the previous iterations and appends your link to each.
Instead of re-gathering them, reuse the existing reference to the container. You can chain append and appendTo.
for (var i = 6; i > 0; i--) {
$('<div class="container"/>') // create container
.append("link" + i + ".php") // append container with link
.appendTo('#everything'); // append container to everything
}
#everything {
padding: 10px;
border: 1px solid blue;
}
.container {
padding: 10px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="everything"></div>
You're giving each div the class of 'container' and then running the append() on all .containers.
You need to give the divs a unique ID, or refer to it directly by the object.
As an example:
for (var i = 6; i > 0; i--) {
$('#everything').append('<div class="container'+i+'"></div>');
var link = "link" + i + ".php" + "<br />";
$('.container'+i).append(link);
}
I need to ask for help.
Having this code:
$(".apprezzamenti").click(function()
{
var id = $(this).attr('id');
$.get("http://localhost/laravel/public/index.php/apprezzamenti_modal/"+id,
function(data)
{
data_parsed = JSON.parse(data);
// BELOW is the loop that I would like to generate multiple div using .append()
for(var i=0; i<data_parsed.length; i++)
{
var html = '<img src="images/provvisorie/immagine-profilo.png" width="30px" and height="30x" />';
html += ' ';
html += "<a href='http://localhost/laravel/public/index.php/utente/" + data_parsed[i].id_user + "' style='font-weight: bold;'>" + data_parsed[i].username + "</a>";
$(".modal-body-apprezzamenti>p").append(html).append('.modal-body-apprezzamenti>p').append($('<br/>'));
}
$(".chiudi-popup").click(function()
{
$(".modal-body-apprezzamenti>p").html('');
});
$('#main').click(function()
{
$(".modal-body-apprezzamenti>p").html('');
});
});
});
I'd like to create a div for each looping.
How could I do? Thanks for your help.
With jQuery it's very easy, look at this JSFiddle
http://jsfiddle.net/Ldh9beLn/
I use the function jQuery appendTo() to insert each div inside another div with id = "inserts" if you don't understand a section of this code or how to adapt to yours leave me a comment.
var things = ["apple", "house", "cloud"];
for (var i = 0; i < things.length; i++) {
$("<div>"+things[i]+"</div>").appendTo("#inserts");
}
Can you please tell me how to make list in jQuery mobile? I am trying to make this type list as given in fiddle on pop up screen dynamically .
Here is the fiddle
In this fiddle I make two rows.In first row there is only p tag. But in second row there is nested collapsible rows. I need to make same thing in pop up screen. I am able to make first row. But In my second row contend is null why? Can you suggest where I am wrong?
fiddle
$(function () {
$('#test').click(function(){
alert('d');
createCommandPopUpTabs();
$("#tabbedPopup").popup("open");
});
});
var tabsHeader = [ "InputParameter", "basic"];
var tabsHeader_basic = [ "XYZ", "Third Level",
];
function createCommandPopUpTabs(){
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("'+
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").append(button);
$("#commandInfoheader").html(header);
for ( var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>InputParameter</h3></div>";
var content ;
if(tabsHeader[i]=="InputParameter"){
content = "<p>yes</p>";
}else if(tabsHeader[i]=="basic"){
for ( var i = 0; i < tabsHeader_basic.length; i++) {
headerId = tabsHeader_basic[i] + "_tab" + commmand;
header = "<div data-role='collapsible' data-collapsed='false' id='"
+ headerId + "'><h3>basic</h3></div>";
content += getcontend(tabsHeader_basic[i]);
}
}
$("#tabbedSet").append(header);
$("#tabbedSet").find("#" + headerId).append(content);
$("#tabbedSet").collapsibleset("refresh");
}
}
function getcontend(name){
if(name=="Third Level"){
return"<p>Third Level></p>";
} if(name=="XYZ"){
return"<p> second Level></p>";
}
}
There are errors in your code and logic. I will only go over a couple of them to hopefully get you on the right path:
In tabsHeader_basic array the Third Level has a space in it which you later use as an ID which makes it an invalid ID because you cannot have spaces in an ID.
From the HTML 5 Draft:
The value must not contain any space characters.
Also, the "basic" collapsible div needs to exist before you start adding the nested collapsible div.
So this line needs to come out of the for loop
header = "<div data-role='collapsible' data-collapsed='false' id='"+ headerId + "'><h3>basic</h3></div>";
Go through the JSFiddle and compare your code agaisnt my changes.
Hopefully that helps! Let me know if you have any other questions.
I have updated createCommandPopUpTabs() function.
Also removed space in Third Level on var tabsHeader_basic = ["XYZ", "ThirdLevel"];
Check the Updated Fiddle
function createCommandPopUpTabs() {
var header = "<h3 >dd</h3>";
var commmand = 'dd';
var button = '<button onclick="return submitCommand("' +
'")" style="" class="donebtn common-button1">Save</button>';
$("#commandInfo").html(button);
$("#commandInfoheader").html(header);
$("#tabbedSet").html('');
for (var i = 0; i < tabsHeader.length; i++) {
var headerId = tabsHeader[i] + "_tab" + commmand;
var header = "<div data-role='collapsible' data-collapsed='true' id='" + headerId + "'><h3>" + tabsHeader[i] + "</h3></div>";
$("#tabbedSet").append(header);
var content;
if (tabsHeader[i] == "InputParameter") {
content = "<p>yes</p>";
$("#tabbedSet").find("#" + headerId).append(content);
} else if (tabsHeader[i] == "basic") {
for (var j = 0; j < tabsHeader_basic.length; j++) {
var headerId1 = tabsHeader_basic[j] + "_tab" + commmand;
var header1 = "<div data-role='collapsible' data-collapsed='true' id='" + headerId1 + "'><h3>" + tabsHeader_basic[j] + "</h3></div>";
var content1 = getcontend(tabsHeader_basic[j]);
$("#tabbedSet").find("#" + headerId).append(header1);
$("#tabbedSet").find("#" + headerId1).append(content1);
}
}
$("#tabbedSet").collapsibleset("refresh");
}
}
I'm creating some ul and span tags dynamically. Now, I'm trying to add content dynamically as well through a click function. The tags gets created inside a ul but the content doesn't get inserted. Here is the code for it:
<div class="main"></div>
<div class="content-list"><ul class="information"> </ul></div>
Here's the Javascript with the function and the listener:
var $contentHandler = $(".content-list");
var $mainHandler = $(".main");
var $infoHandler = $(".information");
var circleCounter = 1;
$mainHandler.click(function() {
var htmlString = "<li class='" + circleCounter + "'> <span class='circle-color'> var color = <div class='circle-color-input' contentEditable autocorrect='off'> type a color</div> ; </span> <br> <span class='circle-radius'> This is supposed to change </span> <br> <span class='circle'> This is supposed to change </span> </li>"
$infoHandler.append(htmlString);
updateList();
circleCounter++;
});
function updateList() {
var listItems = $('.information').find('li#' + circleCounter);
var len = circleCounter;
for (var i = 0; i < len; i++) {
//We create one reference. This makes looking for one element more effective. Unless we need to search for a particular element
var currentItem = circles[i];
var updateStringRadius = "var radius = " + circleCounter + ";";
var updateStringCircle = "circle (" + circleCounter + " ," + circleCounter + ", radius)";
//This is the div Item for the particular div of each element
var divItem = $(listItems[i]);
var radiusItem = divItem.find("span.circle-radius");
var circleItem = divItem.find("span.circle");
radiusItem.text(updateStringRadius);
circleItem.text(updateStringCircle);
// divItem.text(updateString);
var $circleRadiusHandler = $(".circle-radius");
}
}
Any suggestions in how to make it work. Here's a JSFiddle for that:
http://jsfiddle.net/mauricioSanchez/wL6Np/1/
Thank you kindly,
You just need to change:
var listItems = $('.information').find('li#' + circleCounter);//this searches by id
//To:
var listItems = $('.information').find('li.' + circleCounter);//this searches by class`
//And remove:
var currentItem = circles[i];
Why are you trying to edit your HTML after you've defined it? Why not use a template like this:
var listItemClass = 'someclass',
typeOfColor = 'somecolor',
radiusOne = 'someradius',
radiusTwo = 'anotherradius';
var listItem = "<li class='{0}'> \
<span class='circle-color'> var color = \
<div class='circle-color-input' contentEditable autocorrect='off'> {1}</div> ; \
</span> \
<br> \
<span class='circle-radius'>{2}</span> \
<br> \
<span class='circle'>{3}</span> \
</li>";
listItem.format(listItemClass, typeOfColor, radiusOne, radiusTwo);
With the following format definition:
String.prototype.format = String.prototype.f = function () {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
This way, you don't have to worry about finding certain elements within your predefined structure after the fact. You're just replacing certain parts with whatever you specify.
I am appending html to a <ul> on an ajax success function.
HTML
<ul id="revisionList">
<!-- ajax.js will insert ordered list here based on number of revisions -->
</ul>
Ajax Success
success: function(json)
{
/*
If successful build the list of revision links
Links include link that will load images in next tab
*/
//loop through revisions and display
for(i = 0, j = json.revision_count.length; i < j; i++) {
//count for revision number
var k = i + 1;
//revision number, does not match k
var revisionID = json.revision_count[i].layout;
$('#revisionList').append(
"<li><a onclick=\"initEditRevision(" + galleryID + ',' + revisionID + ")\" href=\"#editRev\" data-toggle=\"tab\">Revision " + k + "</a></li>"
);
}
}
How do I go about fading in the whole <ul> after the list is built?
Try this
success: function(json) {
var $list = $('#revisionList');
$list.hide(); // Hide Here
for (i = 0, j = json.revision_count.length; i < j; i++) {
var k = i + 1;
var revisionID = json.revision_count[i].layout;
$list
.append("<li><a onclick=\"initEditRevision(" + galleryID + ',' +
revisionID + ")\" href=\"#editRev\"
data-toggle=\"tab\">Revision " + k + "</a></li>");
}
$list.fadeIn('slow'); // Fade In here
}
for (...
}
$("#revisionList").hide().fadeIn();
Or perhaps you can hide it before the for loop; whatever works best.
You have to hide it using CSS display property firstly or using style attribute if you don't want to use CSS.
#revisionList{display: none;}
OR
<ul id="revisionList" style="display: none;">
then fade in after that all lis appnded completely.
$("#revisionList").fadeIn(500);