Run javascript based on url - javascript

okay so I need this script
$(document).ready(function() {
$('a[id="twittersocial"]').click(function() {
$(".twittersocial").slideToggle("slow", function() {
$(".twittersocial").load('social/twitter.php?k=<?php echo"$website"; ?>', function() {});
});
});
});
to run when someone goes to the direct url
www.website.com#twittersocial
and when of course when somene click the link
twitter social
How can I achieve this ?

When the page is loaded, check whether the hash is set and run your code. Put the code in a function so you can call it from both the event handler and at startup.
$(function() {
function loadTwitterSocial() {
$(".twittersocial").slideToggle("slow", function() {
$(".twittersocial").load('social/twitter.php?k=<?php echo"$website"; ?>', function() {});
});
}
if (location.hash == "#twittersocial") {
loadTwitterSocial();
}
$('a#twittersocial').click(loadTwitterSocial);
}

Related

Call user defined jQuery function with JS

I use a jQuery window libray https://github.com/humaan/Modaal
which triggers events this way $("class of element").modaal({arg1, arg2,...});
--- I updated my question here to make it more general and used an iframe / Html instead of an external svg ---
To trigger an element e.g. in an external Html which is loaded within an iframe, I applied the following code to the iframe:
<iframe src="External.html" id="mainContent" onload="access()"></iframe>
which calls this function:
function access() {
var html = document.getElementById("mainContent").contentDocument.getElementById("IDofDIVelement");
html.addEventListener('click', function() {clicker();});
}
function clicker()
{
// console.log('hooray!');
$("#mainContent").contents().find("IDofDIVelement").modaal({});
//return false;
}
Actually it will only work on every second click. Any idea what I did not consider properly?
Best
You do not need to wait windows loading but iframe only:
$(function() {
$("#mainContent").bind("load",function(){
var myIframeElement = $(this).contents().find(".modaal");
myIframeElement.modaal({
content_source: '#iframe-content',
type: 'inline',
});
});
});
The reason why it did not work was that the iframe was not completely loaded, while jQuery tried to attach the function. As $(document).ready(function(){} did not work, the workaround was to initialize it with
$( window ).on( "load",function() {
$("#mainContent").contents().find("IDofDIVelement").modaal({});
});
This worked properly to attach the functionallity to an element within the iframe.
Actually modaal will vanish the envent handler after the overlay was opened and closed again.
So maybe someone wants to trigger an iframe element for modaal, too, here is a setup which would solve this issue.
(It can be optimised by #SvenLiivaks answer):
$(window).on("load", function() {
reload();
});
function reload() {
var length = $("#iframeID").contents().find("#IDofDIVelement").length;
// The following check will return 1, as the iframe exists.
if (length == 0) {
setTimeout(function() { reload() }, 500);
} else {
$("#iframeID").contents().find("#IDofDIVelement").modaal({
content_source: '#modalwrapper',
overlay_close: true,
after_close: function reattach() {
reload();
}
});
}
}

Get yahoo comments with web scraping

I'm trying to get the news comments on yahoo, where there is a link "See reactions", with the following id: "caascommtbar-wide" and tried to get the element with CasperJS, Selenium, ScrapySharp, to click on the link and display the comments, but in those tools you never find the element and I've even tried using the XPath
CasperJS:
casper.then (function () {
if (this.exists ('a.caascommtbar-anchor')) {
this.echo ("It exists");
} else
this.echo ("It Does not Exist");
});
casper.then (function () {
// Click on 1st result link
this.click ('a.caascommtbar-anchor');
});
Selenium:
driver.FindElement (By.Id ("caascommtbar-anchor")). Click ();
Does anyone know why you can not access this part of the HTML code where the comments are located?
It should be noted that the same thing happens to me when trying to access the Facebook comments contained in the news forums.
As Isaac said the part of pages are loaded asynchronously, so you should implement waitFor steps in your code. Here is the code that does just that.
var url = "https://es-us.vida-estilo.yahoo.com/instagram-cierra-la-cuenta-de-una-modelo-por-ser-gorda-103756072.html";
var casper = require('casper').create({
viewportSize: {width: 1280, height: 800},
});
casper.start(url, function() {
this.echo('Opened page');
});
casper.waitForSelector('a.comments-title', function() {
this.click('.comments-title');
});
casper.waitForSelector('ul.comments-list > li', function() {
this.echo(this.getHTML('ul.comments-list'));
});
casper.run();
Hope that helps
The problem was why the page was not loaded yet and I had to wait, I'm new with casperjs.
Now I have the problem when trying to remove all comments along with their answers, but can not find an algorithm to help me. Try to press all the answer buttons, but only get the first answers to the first comments.
casper.waitForSelector('button.showMore', function () {
this.click('.showMore');
}, function onWaitTimeout() {
});
var buttons;
casper.waitForSelector('ul.comments-list', function getLinks() {
buttons = this.evaluate(function ()
{
var buttons = document.getElementsByClassName('replies-button');
buttons = Array.prototype.map.call(buttons, function (button) {
button.click();
casper.waitForSelector('ul.comments-list', function () {
casper.wait(3000, function () {
});
});
return button.getAttribute('class');
});
return buttons;
});
}, function onWaitTimeout() {
});
function wait5seconds() {
casper.wait(3000, function () {
});
}
casper.waitForSelector('ul.comments-list > li', function () {
var x = this.getHTML('ul.comments-list');
this.echo(x);
}, function onWaitTimeout() {
});
casper.run();

JQuery function POST on the same page works only twice

The function below allows me to use an href link to POST request to the same page. It works for the first 2 times I click on the link, but this function doesn't seem to be recognized after a third POST request.
$(function() {
$('.sort-link').on('click', function(e) {
e.preventDefault();
$.post(this.href, function(data) {
$('.container').html(data);
});
});
});
I need to modify the function to have it work even after a POST request has been submitted.
As per #Elvin85's advice, I revised my function as follows:
$(function() {
$(document).on("click", '.sort-link', function(e) {
e.preventDefault();
$.post(this.href, function(data) {
$('.container').html(data);
});
});
});
It was a DOM-related issue.

Structure javascript and delay execution when dynamically loading scripts

I'm loading my javascript files using Modernizr.load(). Now lets say each page needs to call their own init method after everything has finished loading. But I put the loading in a template master, which is unaware of the child pages. How can the pages know when the dependencies have finished loading?
script
Page1Stuff= {
init: function(){ alert('page 1 executed'); }
}
Page2Stuff= {
init: function(){ alert('page 2 executed'); }
}
site master template
//Modernizr loads the script.
Modernizr.load([{
load: 'jquery.js',
},
{
load: 'script.js'
}]);
page1
$(function() {
Page1Stuff.init();
});
page2
$(function() {
Page2Stuff.init();
});
I think I see 2 problems here. If modernizr is still loading jquery, $ may not be defined. Also, Page2Stuff or Page1Stuff may not be defined.
In your template: Use the modernizer "complete" call back to emit a custom event to signal the loading is complete, also set a global variable saying that the scripts have been loaded.
In your page scripts: first check the global variable to see if all scripts have been loaded, if not, register a handler to listen for the custom event you emit when the loading completes.
In your template code:
// A simple object that calls its listeners when modernizer script loading completes.
global_scriptLoadingMonitor = (function() {
var listeners = [];
var isComplete = false;
return {
"addListener": function (listener) {
listeners[listeners.length] = listener;
},
"complete": function () {
isComplete = true;
for (var i = listeners.length - 1; i >= 0; i--) {
listeners[i]();
}
},
"isComplete": isComplete
}
})();
Modernizr.load([{
load: 'jquery.js',
},
{
load: 'script.js'
complete: function () {
{
global_scriptLoadingMonitor.complete();
}
}]);
Now in your Page1 do this:
if (global_scriptLoadingMonitor.isComplete) {
$(function() {
Page1Stuff.init();
});
} else {
global_scriptLoadingMonitor.addListener(function() {
$(function() {
Page1Stuff.init();
});
});
}
And similarly for page2.

Question about Javascript (Jquery) and GET

After getting a new page with $.get none of the javascript will run on the new page.
Is there a way to make javascript use the new page too?
Many thanks
Dorjan
Edit: Example:
$(function() {
$('.viewPage').click(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Now this works fine however, the new page's anchor tags won't trigger (lets say it has a .viewPage).
I hope that clarify's the issue.
You need to bind events to your anchors using live:
$('a.something').live("click",function() {
alert('this will still work after a.something has been replaced via ajax');
});
Another way using $.get's callback:
$.get( "page.html", function(data) {
$('#someDiv').html(data);
$('a.something').click(function() {
alert('this will still work after a.something has been replaced via ajax');
});
});
Now that I've seen your code:
$(function() {
$('.viewPage').live("click",(function() {
$('#mainarticle').fadeOut('slow')
$.get($(this).attr('href'), { js: "1" }, function(data) {
$('#mainarticle').html(data).fadeIn('slow');
});
return false;
});
});
Yep; there is another jquery ajax method that will take the returned script from your page and execute it. Check the jquery docs.

Categories