Get URL To Add Inline Style - javascript

I'm using Blogger and on the "Preview" post page, it is hiding an element with 'display:none'. What I am trying to do, is use javascript to apply 'display:block' to that element during the "Preview".
I have to use javascript, because Blogger doesn't have any kind of XML conditional statement I can use; and default styling cannot be changed.
The URL looks something like this: https://myblogexample.blogspot.com/b/post-preview?token=XXXXXXXXXXXXXXXXXXXXXXXXXX&type=POST
The token is obviously always random. So how can I grab the part of the URL and apply an inline style to a particular element? My javascript skills suck, but this is what I came up with, and it doesn't work...
$(document).ready(function(){
if((window.location.protocol + "//" + window.location.host + "/b/post-preview) = document.getElementById('Main-Section').style.display = 'block'})
});

Your javascript code is not valid, it can't be parsed by the browser.
You are asking to show some part of the page when you are in the page "yourbloghost.com/b/post-preview?token=something", right?
You can do this with something like:
$(document).ready(function(){
if (window.location.pathname == "/b/post-preview")
{
document.getElementById('Main-Section').style.display = 'block';
}
});
or also:
$(document).ready(function(){
if (window.location.pathname == "/b/post-preview")
{
$("#Main-Section").show();
}
});

Related

jQuery Adding Extra Parameters

I have the following jQuery Code which I'm using to show or hide a particular section from the page:
<script>
if(location.search == "?show=success"){
$('.step, #step1').hide();
$('.success').show();
location.hash = 'ka?show=success';
}
if(location.search == "?show=successtwo"){
$('.step, #step1, #FlowFour2').hide();
$('.success-two').show();
location.hash = 'ka?show=successtwo';
}
</script>
It actually works, but in the process also adds extra parameters to the final URL.
So if I access http://example.com/ka/?show=success, I get redirected to http://example.com/ka/?show=success#ka?show=success
Can someone help in this please?

Find closest class and reload it AJAX jQuery

This is a "LIKE" system similar to Facebook.
I've got an html layout with multiple links where each one looks something like this when rendered :
<a class="like-comment-link" href="#" data-id="278">
<span class="like-comment"></span></a>
<span class="likes">Bob, John and Peter like this</span>
I'm using AJAX to insert and delete the likes into the database, this is all working great. But I'm having trouble targeting the "likes" class from the ajax script to update the names of the people that liked it.
I basically need something which does the following :
$(this).closest(".likes").find(".likes").load(location.href + " .likes");
I know this doesn't work but I don't know the correct way to code it.
Basically, on a successful like or unlike I need jQuery to find the closest instance of ".likes" to the parent which is ".like-comment-link" and then reload that class only on this element.
EDIT
Including AJAX script
$(document).ready(function(){
$(document).on('click', "a.like-comment-link", function(event) {
event.preventDefault();
var $self = $(this);
var data = {
post_id: $self.data('id'),
nonce: likecom.nonce,
action: 'comment_likes'
};
$self.addClass('loading');
$.post(likecom.ajaxurl, data, function(res) {
if (res.success) {
$self.html(res.data);
$self.siblings(".likes").load(location.href + " .likes");
} else {
alert("It went tits up!");
}
$self.removeClass('loading');
});
});
});
If this is overly complicated I could change target class' name to include the id of the current item like this :
<span class="likes-278">....</span>
But I can't figure out how to concatenate strings in jQuery.
I tried a few things like this :
$(".likes-" + $self.data('id')).load(location.href + " .likes-" + $self.data('id'));
But that obviously didn't work.
Maybe somebody could show me how to correctly formulate this in the AJAX script?
You may try something like this. Since the span is always after the anchor element in your example, you may also use .next() function to locate the element
$('.like-comment-link').on("click",function()
{
if($(this).next("span").hasClass("likes"))
{
$(this).next("span").removeClass("likes");
$(this).next("span").addClass("nolikes");
// Write value to db
}
else
{
$(this).next("span").removeClass("nolikes");
$(this).next("span").addClass("likes");
// Write value to db
}
});
http://jsfiddle.net/3k0vLdt4/3/
Hope it helps doing what you want to do.

change url to reflect content on the page hidden / displayed with Javascript

I am currently making a website for an architecture firm, HLArchitects. In the projects page I have created an HTML / Javascript image gallery. slightly above the main big image to the right an option can be found to choose between images / information. I use Jquery to show and hide the information or the images, however i don't feel this is such a great way to do so. It can be viewed here for reference: http://www.hla.co.za/projects/Hyuandai_Training_Centre/
Here is the relevant Javascript:
$(".selector a").click(function(){
if ($(this).attr("data-show") == "images") {
$("#info").fadeOut("fast");
$("#displayImg").fadeIn("fast");
$("#imageFlow").fadeIn("fast");
} else if ($(this).attr("data-show") == "info") {
$("#displayImg").fadeOut("fast");
$("#imageFlow").fadeOut("fast");
$("#info").fadeIn("fast");
}
})
Relevant HTML:
<p class="selector">images | information</p>
My problem is that the url does not change to reflect the content, but I do not want to make a separate page. I could imagine i would need to make use of link anchor's but am not to sure how to do so.
Thank you in advance
You can change the hash of an url by using:
window.location.hash = 'images';
EDIT:
Firstly, in this context you don't need to include the hash symbol!
Secondly, I missed the obvious, you only need to change the HTML to this to update the URL correctly:
<p class="selector">
images
information
</p>
Then you can use the following in your jQuery, note I've included the attribute check inside the selector itself:
$(".selector a[href=#images]").click(function() {
$("#info").fadeOut("fast");
$("#displayImg").fadeIn("fast");
$("#imageFlow").fadeIn("fast");
});
$(".selector a[href=#info]").click(function() {
$("#displayImg").fadeOut("fast");
$("#imageFlow").fadeOut("fast");
$("#info").fadeIn("fast");
});
If you want to refresh the page and get the same content, you can check the hash tag by doing the following (you may need to edit this depending what elements are showing initially):
$(document).ready(function() {
if (window.location.hash == '#images') {
$("#info").hide();
$("#displayImg").show()
$("#imageFlow").show();
}
else if (window.location.hash == '#info') {
$("#displayImg").hide();
$("#imageFlow").hide();
$("#info").show();
}
});
If all you're doing is setting text in the URL, you can do this easily by setting location.hash
location.hash="#SomeTextHereThatMayOrMayNotNecessarilyBeAnAnchor"
^ Note that "#" is important

JQuery hide div based on url hash and string

I'm attempting to hide a div based on the url hash tag. I'm using a jquery plugin called zozo tabs that allows for deep-linking and it shows and hides divs.
There is a particular div on the page (not in the tab area) I would like to hide given the url/s. I've searched but cannot figure it out. Please excuse my javascript noobness!!! I've tried this. No such luck. It doesnt seem to work. Any help would greatly appreciated.
I've tried php but it doesnt work on the hash
To start the plugin creates this type of url
http://localhost:8888/site/funds/#tabbed-nav=fund-strategy
The html is:
<ul>
<li data-link="fund-strategy"><a>Fund Strategy</a></li>
<li data-link="portfolio-characteristics"><a>Portfolio Characteristics</a></li>
<li data-link="performance"><a>Performance</a></li>
</ul>
<div class="strategy">This copy shows when the li is clicked on</div>
This is me attempting to hide a div given the url with js
var jQ = jQuery.noConflict();
jQ(document).ready(function() {
var url = document.location.href;
if (url.indexOf('http://localhost:8888/site/funds/#tabbed-nav=fund-strategy') >= 0) {
jQ('.fourth').hide();
};
});
<div class="fourth">Hide me please!</div>
Just try to use something like this:
var currentHash = window.location.hash;
if (currentHash=="#tabbed-nav=fund-strategy") {
$('.fourth').hide();
}
Be sure that there is a html element with class 'fourth' in your html code. Otherwise this will not hide anything.
I think i pinpointed the problem. The zozo tabs utilizes hashchange. So after hitting my head against the wall and HUGE inspiration from users here. I downloaded the ba.hashchange and wrapped the given answers in a hashchange function here is the code if anyone is interested. This seemed to work.
var jz = jQuery.noConflict();
jz(function(){
jz(window).hashchange( function(){
// Alerts every time the hash changes!
var hash = document.location.hash;
if (hash == '#tabbed-nav=risk' || hash == '#tabbed-nav=fund-strategy') {
jz('.fourths').show();
} else {
jz('.fourths').hide();
}
})
jz(window).hashchange();
});

reinitialize processing.js sketch after ajax request

I would like to refire the styling and processing.js scripts that i linked to in the head so that they display correctly when brought in through an ajax-request. I see where in the ajax request this code needs to be, but i don't know how to tell the code to simply reapply the script. I've seen people using getScript() to do this, but from what i can tell this reloads the script, rather than simply telling it repeat or refire. Do all of the scripts need their own reinitialization? I found the syntax highlighters .highlight() method, but i am yet to get the processing script to load. currently, Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']); does not work. I am using current versions of all libraries. Surprised i haven't been able to find the answer yet, as a lot of people seem to have the same problem. Thanks for your help!
index page:
$(document).ready(function () {
// put all your jQuery here.
//Check if url hash value exists (for bookmark)
$.history.init(pageload);
//highlight the selected link
$('a[href=' + document.location.hash + ']').addClass('selected');
//Search for link with REL set to ajax
$('a[rel=ajax]').live("click",function(){
//grab the full url
var hash = this.href;
//remove the # value
hash = hash.replace(/^.*#/, '');
//for back button
$.history.load(hash);
//clear the selected class and add the class class to the selected link
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
//hide the content and show the progress bar
//$('#content').hide();
$('#loading').show();
//run the ajax
getPage();
//cancel the anchor tag behaviour
return false;
});
});
function pageload(hash) {
//if hash value exists, run the ajax
if (hash) getPage();
}
function getPage() {
//generate the parameter for the php script
var data = 'page=' + encodeURIComponent(document.location.hash);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
//hide the progress bar
$('#loading').hide();
//add the content retrieved from ajax and put it in the #content div
$('#content').html(html);
//display the body with fadeIn transition
$('#content').fadeIn('fast');
//reapply styles?
//apply syntax highlighting. this works
SyntaxHighlighter.highlight();
//relaod processing sketch, currently displays nothing
Processing.loadSketchFromSources($('#processing'), ['mysketch.pde']);
}
});
}
This the ajax-loaded content:
<!--ajax'd content-->
<??>
<h2>code</h2>
<pre class="brush: php">
$last_modified = filemtime("header.php");
echo("last modified: ");
echo(date("m.j.y h:ia", $last_modified));
</pre>
<script type="application/processing">
</script>
<canvas data-processing-sources="mysketch.pde" id="processing">
</canvas>
</div>
</body>
</html>
<??>
So, let's analyze what usually happens when you include an (external or internal) Javascript code: It will automatically execute only the code that is available in the global scope. "Good" scripts will only add one command to the global scope which will then execute the initialization code somewhere in a function/method.
All you need to do is view the external Javascript file and find out what is being executed from the global scope. There is no general answer to that ... some scripts use an object and call its init() method ... but that is totally subject to the imagination of the developer.
If you have javascript that needs to trigger, you MUST add this to the head element:
var head = document.head || document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.innerHTML = "your AJAX-obtained js code";
head.appendChild(script);
The same trick goes for CSS. Add a element to the head with your CSS declarations as innerHTML. So: make sure to preprocess your AJAX response and split out the JavaScript and CSS elements, then add those to the document header. It's probably easier to make your response a JSON object along the lines of:
{
html: "<html>string<goes>here</goes></html>",
scripts: ["url1","url2","url2",...],
style: ...
}
and then parsing that JSON for the html (which you use as innerHTML for a new document.createElement("div") or something, and then append wherever it needs appending), the scripts (which you turn into elements for HEAD insertion) and the style declarations (which you turn into elements for HEAD insertion).
(On a functional note, your example AJAX response looks like it has PHP code in it. I have no idea what you're using it for, but that looks like a bad response)
Just incase anyone stumbles upon this:
If you have processing.js already loaded, simply call Processing.reload() in your AJAX success/complete function.
Perhaps you already have an element with id="processing" on your page. In that case $("#processing") will only return the first one. If that is the case, change the id or use a class instead.
The other option, which I don't recommend, is to use $("[id=processing]"). That will return every element on the page with id="processing". But, don't use it. Use unique ids in your page, or switch to using classes, whichever works best for you.

Categories

Resources