On setting background in a div using jQuery and JSON... - javascript

I've been working on a way to get an species of database with only JSON and I managed to get it working [who knew that a "js/" in the url would make it work? :'(]
But that's not the problem, now I got an issue with CSS. Well, let's explain it.
I have this JSON:
[
{
"title":"Facebook",
"url":"http://www.facebook.com",
"bg":"../img/facebook.png"
},
{
"title":"Twitter",
"url":"http://twitter.com",
"bg":"../img/twitter.png"
}
]
This Markup:
<section id="links">
<!-- here should be the <a>'s -->
</section>
And this JavaScript (using jQuery):
$(function(){
$.getJSON('js/links.json', function(data){
$.each(data, function(index){
$("#links").append('<span>'+data[index].title+'</span>');
});
});
});
Now you say: It should work. And sure it works, but the background simply does not display. Seems that HTML goes nuts as I've seen in the inspector.
Ok, then, what's wrong and what should I change?

I think the problem could be the way you have defined the style attribute.
style="background-image:url("'+data[index].bg+'");
The quotation mark directly after the opening parentheses is closing your style attribute. I would think simply removing it would do the trick
style="background-image:url('+data[index].bg+');
alternatively, replacing the double quote with an escaped single quote should also work
style="background-image:url(\''+data[index].bg+'\');

You need to escape your " " " with backslashes **\**

Related

How to use Javascript to change href and html text?

So I've got this little piece of HTML that I have zero access to, and I need to change the URL of where it's linking, to somewhere else.
Now I've looked around, and I've tried different approaches and non seem to work so I must be doing something wrong.
the Html code:
<div class="manageable-content" data-container="edit_register_ind_container">
<a class="entry-text-link secondary-step step-button" id="register_ind_container" href="oldurl">Register</a>
</div>
First I wanted to try something that seemed easier, which was to change the displayed text "Register" to "Start a Fundraiser"
This is what I have got for that part:
// url manipulation
$(document).ready(function(){
$("#register_ind_container").click(function(){
$("#manageable-content a").text('Start a Fundraiser');
});
$("#register_ind_container").attr("href", "http://google.ca");
});
No luck so far for any of it.
a little background information:
I am using a platform called Luminate/Blackbaud, its a CMS with a weird set up. header tags and stuff like that go in a different place than the html body and the css is somewhere else as well (but I'm just using ftp to reference it in the header).
How I'm referencing the javascript code.
<script type="text/javascript" src="../mResonsive/js/urlmanipulation.js"></script>
My css works so I'm certain this should to, but I just don't know why it isn't.
All suggestions welcome (except for asking for the html access because I have, 3 weeks ago lol)
Thank you for your time!
I saw your both code :
$("#register_ind_container").attr("href", "http://google.ca");
This line will execute on page load so href should be changed on load
$("#register_ind_container").click(function(){
But when you performing this click on Id
it wont work because at that instance this id associated with an hyperlink
so hyperlink having the default subset rules
for Overriding this you can try
$("#register_ind_container").click(function(e){
// custom handling here
e.preventDefault();
$(this).text('Start a Fundraiser');
});
But this is also not a Good Practice. Hope this helps !
$(document).ready(function(){
$("#register_ind_container").click(function(){
$(this).text('Start a Fundraiser');
$(this).attr("href", "http://google.ca");
});
});
You are changing the URL outside the click event.. Wrap it inside the click event.. Also make use of $(this)
// url manipulation
$(document).ready(function(){
$("#register_ind_container").click(function(){
$(this).text('Start a Fundraiser').attr("href", "http://google.ca");
});
});

Javascript/jQuery Dynamic text to link/href replece

I need to replace and convert to URL following words on my entire site; Square-Technology UK. I've done some research into replacing text displayed within a site to replace it with url.
Here is the code:
http://jsfiddle.net/Hgtrh/1/
However it doesn't replace on my website for some reason. Here is the HTML am using.
<div class="main_testimonials">
<div class="c_box"></div>
<div class="main_content_img">
<img src="images/news/thumbs/1184901_10151885560986667_1371257993_n_t2.jpg" alt="News" class="news-category"></div>
<div class="main_bubble_box">
Thank you Square-Technology UK for my new system!!
</div>
</div>
this is an example of different javascipt that works, note the ' and "
echo "<script type='text/javascript'>
$(document).ready(function() {
$('body').removeClass('no-js'); $('#my-carousel-3').carousel({ itemsPerPage: 3, itemsPerTransition: 3, easing: 'swing', noOfRows: 1 }); });</script>\n";
Right managed to solve this very easily. My script didn't allow me to use double quotes inside the echo tag in PHP, which is quite obvious. Alternatively using single quotes does not work using the script I posted at the beginning. However the way to do it is just create another file.js, place the code inside it, and then attach it using the following:
echo"<script type='text/javascript' src='js/test_replace.js'></script>\n";
Did you try this?
$(document).ready(function() {
var thePage = $("body");
thePage.html(thePage.html().replace(/Square-Technology UK/ig, 'Square-Technology UK'));
})
Hope this helps..
Try using a more specific identifier to track what you want to replace instead of tracing the entire DOM to search for what you want to replace:
JS:
$(function() {
var $siteLink = $('.site-link'),
linkHtml = 'Square-Technology UK';
$siteLink.html(linkHtml);
});
HTML:
<span class="site-link"></span>
However since your fiddle seems to work we can only guess what is happening, can you provide more info about what jquery you are running, or how the page is layout.
Here is a Fiddle: http://jsfiddle.net/Hgtrh/4/
It is also worth mentioning just like ikaros45 said, that this is normally not something you would want to do with Javascript, this seems more like something that the templates should be able to deal with.
It works on your fiddler example, but not on your site. I suggest confirming that the JQuery library is loading on your site as expected.
So I managed to solve this very easily. My script didn't allow me to use double quotes inside the echo tag in PHP, which is quite obvious. Alternatively using single quotes does not work using the script I posted at the beginning. However the way to do it is just create another file.js, place the code inside it, and then attach it using the following:
echo"<script type='text/javascript' src='js/test_replace.js'></script>\n";

Why doesn't my javascript onclick work with div?

I am trying to turn a <div> into a link to local HTML document (./lilo/index.html) using JavaScript.
HTML
<div class="pagelist_item" onClick="goto("./lilo")">
<h4>Test Button</h4>
<h6>Discription</h6>
</div>
JavaScript
function goto(url){
window.location = url;
alert(url);
}
See http://jsfiddle.net/6HHTd/
But when I click the button, nothing happens.
Why does this not work?
Your quotes are incorrect in this line:
<div class="pagelist_item" onClick="goto("./lilo")">
jsfiddle even shows the error in red text.
Using apostrophes makes it easier to fix:
<div class="pagelist_item" onClick="goto('./lilo')">
To clarify, in "hi "there" you" the second double-quote matches with the first, closing the string and causing an error with the rest of the expression. Escaping the quotes with back-slashes works "hi \"there\" you" but embedding apostrophes (single-quotes) within double-quotes is often easier. (JavaScript is happy to use either single or double-quotes to delimit strings.)
Also rename your function from goto, as it is a reserved keyword.
Use jquery as follows
$('.pagelist_item').click(function(){
window.location="./lilo";
});
Fiddle

Cannot match pattern for wordpress empty paragraph tag

For some reason wordpress randomly inserts "blank" paragraph tags on my page. I'm finding it difficult to match the tag.. It seems like it's not completly empty but some weird character I cannot see, it's not there in the source code but generated by javascript so it's very hard to figure out what it is!!
My JS file is loaded last in <head>.
I'm new to regex in javascript..
it looks like this in firebug (not sure if there is a small space/tab/something or not)
<p></p>
My javascript to remove it:
jQuery(window).load(function() {
var page = jQuery('body').html();
page.replace('/\<p\>\S*\<\/p\>/', '');
jQuery('body').html(page);
});
Use jQuery empty selector instead which select all elements that have no children (including text nodes). Try this.
jQuery(window).load(function() {
jQuery('body').find('p:empty').remove();
});
You know the exact string, so what's the matter with just matching just that?
page.replace('/\<p\>\<\/p\>/','');

Expansion of Struts 2 Tags Messes Up Rendering Of Page

Often times, when I use struts 2 tags, the loading of a page will be incomplete apparently because of single quote or double quote characters from the struts 2 tag interfering with such characters from javascript.
One example I am very eager to get working is as follows:
var me = '<s:a href=\'http://www.google.com\'>Google Link</s:a>';
$('#appnSelect').html(me);
So what I am concerned about is when single and double quotes are inside that me string on the right side of line 1. Ultimately, I need to get <s:select> to work, but this problem seems to creep in with a number of tags like the above example. Replace the <s:a> tag with an <a> tag, and voila, it works. However, when the <s:a> tag gets expanded, the page will incompletely load.
Is there an easy solution somewhere I am missing? One thing I did try was with the theme attribute setting theme="simple" because sometimes that helps me when the output gets rendered incorrectly. That did not work in this case.
Generating HTML from tags like that in the middle of a JavaScript string constant is always going to be an ugly business. In addition to quote characters, you're also likely to get newlines. Strictly speaking you don't know what you're going to get, and you can't control it.
One thing that comes to mind is that you could drop the tags into dummy <script> blocks marked as a non-JavaScript type:
<script id='anAnchor' type='text/html'>
<s:a href='http://www.google.com'>Google Link</s:a>
</script>
The browser won't try to execute that. You can then do this in your JavaScript code:
$('#appnSelect').html($('#anAnchor').html());
What should work with very little thinking:
<s:a id="google" style="display: none;" href="www.google.com">Google Link</s:a>
Now just grab the the element using the id in your script. Might be better if you set up a class. There are id, style and class attributes for all struts2 tags.
I believe the issue is with your escaping of the single quotes inside the <s:a> tag. In my experience with using <s:url>, I've done the following:
var url = "<s:url value='/someAction.action' />"
I believe the same syntax should hold true for <s:a>.
Additionally, look in your JSP container's error log, and see if you can find an error relating to that <s:a> tag. That may provide some additional insight to the problem.
This is my answer, which will not be the best answer because Pointy's response pointed me in the correct direction. However, up votes still appreciated :)
First, you need the script blocks which are not rendered. I have 2 because a checkbox will toggle between which one is displayed:
<script type="myType" id="abc">
<s:select name="selectName" list="#list1" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
<script type="myType" id="abc2">
<s:select name="selectName" list="#list2" listValue="%{prefix + '-' + name}" theme="simple"/>
</script>
Next, I create a region which is blank in the html code
<div id="innerRegion">
</div>
Then, I need to put something on the screen when the page first comes up, so go with this:
<script type="text/javascript">
$(document).ready(function(){
$('#innerRegion').html( $('#abc').html() )
});
I needed to put this at the end of my document because onLoad was already being used by a parent page. So I am saying abc is the correct default.
Then I need logic to handle what happens when the checkbox is pushed:
var buttonPressed = false;
$(window).load(
function()
{
LocalInit();
});
function LocalInit() {
$('#myForm input[name=buttonValue]').change(
function()
{
buttonPressed = !buttonPressed;
if (buttonPressed == true)
{
$('#innerRegion').html( $('#abc2').html() )
} else
{
$('#innerRegion').html( $('#abc').html() )
}
$('#dataId').href = document.location.href;
}
);
}
I think what was tripping me up ultimately was that I was trying to force the s:select tag through jQuery functions when as you see above it did not turn out to be necessary. I could just write the s:select as normal.

Categories