I have been looking into this issue for the past few days and cannot figure it out. The code below, searches an external file for content based off current page class, then loads content into any matching ID's on the page. It works in Chrome, Firefox, IE9 but recently stopped working in IE8 and I cannot figure out why. Any thoughts would be much appreciated.
HTML looks like this
<body class="jms">
<div id="mainHomeContent" class="shared"></div>
</body>
jquery running on ready
$("div.shared").each(function(){
var Body = $(document).find("body");
var contentID = ("#" + $(this).attr("id"));
var pathname = ""
if(Body.hasClass("pigman")){
var pathname = "/dev/jmsracing/content/pigman/shared-content-include.html"
} else if(Body.hasClass("marion-arts")){
var pathname = "/dev/jmsracing/content/marion-arts/shared-content-include.html"
} else if(Body.hasClass("jms")){
var pathname = "/dev/jmsracing/content/jms/shared-content-include.html"
alert('hello');
}
$(contentID).load(pathname + " " + contentID);
});
What i think is he is iterating with same id where ie is very strict about it so this should be the solution:
$(function() {
var Body = $(document).find("body");
var contentID = ("#" + $(this).attr("id"));
var pathname = ""
if (Body.hasClass("pigman")) {
var pathname = "/dev/jmsracing/content/pigman/shared-content-include.html"
} else if (Body.hasClass("marion-arts")) {
var pathname = "/dev/jmsracing/content/marion-arts/shared-content-include.html"
} else if (Body.hasClass("jms")) {
var pathname = "/dev/jmsracing/content/jms/shared-content-include.html"
alert('hello');
}
$(contentID).load(pathname + " " + contentID);
});
Try this:
$("div.shared").each(function () {
//combined into one var statement...not really necessary.
var $body = $("body"),
contentId = "#" + $(this).attr("id"),
pathname = "";
//you've declared pathname above no need for "var" each time below
//also added missing semi colons
if ($body.hasClass("pigman")) {
pathname = "/dev/jmsracing/content/pigman/shared-content-include.html";
} else if ($body.hasClass("marion-arts")) {
pathname = "/dev/jmsracing/content/marion-arts/shared-content-include.html";
} else if ($body.hasClass("jms")) {
pathname = "/dev/jmsracing/content/jms/shared-content-include.html";
alert('hello');
}
// $(this) and $(contentId) are the same element
// since you are getting the "id" from "this"
// us $(this) instead
$(this).load(pathname + " " + contentId);
});
Related
This is my setup
<script>
$(document).ready(function() {
document.querySelectorAll(".money").forEach(function(e) {
e.addEventListener("click", function() {
setTimeout(function() {
myfunction();
}, 300);
});
});
});
function myfunction() {
var urlParams = window.location.search;
var typ = "produkttyp=Tasting";
var urlParamsUpdate = typ.slice(0,-3)+ urlParams + typ.slice(-1);
var newUrl = "/collections/alle/" + urlParamsUpdate;
window.location.href = newUrl.slice(0, -2) + "0%2C" + newUrl.slice(-2);
}
</script>
The result is the following url:
produkttyp=Tast?kategorie=Rotwein&money=10%2C0g
But thats not the result i am looking for. The wanted result is:
?produkttyp=Tasting&kategorie=Rotwein&money=0%2C25
So bascially I just want the ?produkttyp=Tasting& as the first search parameter, but its not working out. The mistake is somewhere here. I cant slice it the right way.
var urlParamsUpdate = typ.slice(0,-3)+ urlParams + typ.slice(-1);
Can somebody help me out?
I found a workaround:
<script>
$(document).ready(function() {
document.querySelectorAll(".money").forEach(function(e) {
e.addEventListener("click", function() {
setTimeout(function() {
myfunction();
}, 300);
});
});
});
function myfunction() {
var urlParams = window.location.search;
const urlParamsUpdate = urlParams.slice(1);
const urlUpdateMoney = urlParamsUpdate.slice(0, -2) + "0%2C" + urlParamsUpdate.slice(-2);
const url = "?produkttyp=tasting&";
window.location.href = "/pages/..." + url + urlUpdateMoney ;
}
</script>
Now I am just slicing away the "?" from the urlParams and then insert the missing part of the url "?produkttyp=tasting&" in the first place.
I'm having trouble clicking all JavaScript based links in a DOM and saving the
output. The links have the form
<a id="html" href="javascript:void(0);" onclick="goToHtml();">HTML</a>
the following code works great:
var casper = require('casper').create();
var fs = require('fs');
var firstUrl = 'http://www.testurl.com/test.html';
var css_selector = '#jan_html';
casper.start(firstUrl);
casper.thenClick(css_selector, function(){
console.log("whoop");
});
casper.waitFor(function check() {
return this.getCurrentUrl() != firstUrl;
}, function then() {
console.log(this.getCurrentUrl());
var file_title = this.getTitle().split(' ').join('_') + '.html';
fs.write(file_title, this.getPageContent());
});
casper.run();
However, how can I get this to work with a selector of "a", clicking all
available links and saving content? I'm not sure how to get the clickWhileSelector to remove nodes from the selector as is done here: Click on all links matching a selector
I have this script that first will get all links from a page then save 'href' attributes to an array, then will iterate over this array and then open each link one by one and echo the url :
var casper = require('casper').create({
logLevel:"verbose",
debug:true
});
var links;
casper.start('http://localhost:8000');
casper.then(function getLinks(){
links = this.evaluate(function(){
var links = document.getElementsByTagName('a');
links = Array.prototype.map.call(links,function(link){
return link.getAttribute('href');
});
return links;
});
});
casper.then(function(){
this.each(links,function(self,link){
self.thenOpen(link,function(a){
this.echo(this.getCurrentUrl());
});
});
});
casper.run(function(){
this.exit();
});
rusln's answer works great if all the links have a meaningful href attribute (actual URL). If you want to click every a that also triggers a javascript function, you may need to iterate some other way over the elements.
I propose using the XPath generator from stijn de ryck for an element.
You can then sample all XPaths that are on the page.
Then you open the page for every a that you have the XPath for and click it by XPath.
Wait a little if it is a single page application
Do something
var startURL = 'http://localhost:8000',
xPaths
x = require('casper').selectXPath;
casper.start(startURL);
casper.then(function getLinks(){
xPaths = this.evaluate(function(){
// copied from https://stackoverflow.com/a/5178132/1816580
function createXPathFromElement(elm) {
var allNodes = document.getElementsByTagName('*');
for (var segs = []; elm && elm.nodeType == 1; elm = elm.parentNode) {
if (elm.hasAttribute('id')) {
var uniqueIdCount = 0;
for (var n=0;n < allNodes.length;n++) {
if (allNodes[n].hasAttribute('id') && allNodes[n].id == elm.id) uniqueIdCount++;
if (uniqueIdCount > 1) break;
};
if ( uniqueIdCount == 1) {
segs.unshift('id("' + elm.getAttribute('id') + '")');
return segs.join('/');
} else {
segs.unshift(elm.localName.toLowerCase() + '[#id="' + elm.getAttribute('id') + '"]');
}
} else if (elm.hasAttribute('class')) {
segs.unshift(elm.localName.toLowerCase() + '[#class="' + elm.getAttribute('class') + '"]');
} else {
for (i = 1, sib = elm.previousSibling; sib; sib = sib.previousSibling) {
if (sib.localName == elm.localName) i++; };
segs.unshift(elm.localName.toLowerCase() + '[' + i + ']');
};
};
return segs.length ? '/' + segs.join('/') : null;
};
var links = document.getElementsByTagName('a');
var xPaths = Array.prototype.map.call(links, createXPathFromElement);
return xPaths;
});
});
casper.then(function(){
this.each(xPaths, function(self, xpath){
self.thenOpen(startURL);
self.thenClick(x(xpath));
// waiting some time may be necessary for single page applications
self.wait(1000);
self.then(function(a){
// do something meaningful here
this.echo(this.getCurrentUrl());
});
// Uncomment the following line in case each click opens a new page instead of staying at the same page
//self.back()
});
});
casper.run(function(){
this.exit();
});
I made a function to add <a> tag in chat text and it worked fine, but it seems the variables of the function are shared between different instances of the function called from different chat rooms. I thought function variable were local, can anyone explain why I'm encountering this problem? Well I found out the code was wrong and a <p> tag the ajax function was adding to the string was interfering with this function. i fixed it by adding a space before the conflicting <p> tag and now it works fine...updated the code with english variable names too :)
function ajoutertagdelien(dataChat)
{
if (dataChat)
{
}
else
{
dataChat = " ";
}
var chatsendvar = dataChat;
var linkLocation, chatStringLeftPiece, chatfinal = "", chatStringRightPiece, lienfin, LinkAlone, LinktagString, LinkPiece;
var linkTagA = new Array();
var variablelocation = new Array();
var variablechatsend = new Array();
var increment=0;
var earlierLinkLength = 0;
linkLocation = chatsendvar.indexOf("www.");
while (linkLocation != -1) {
increment++;//
if (linkLocation != -1)
{
chatStringLeftPiece = chatsendvar.substring(0,linkLocation);
LinkPiece = chatsendvar.slice(linkLocation,chatsendvar.length);
lienfin = LinkPiece.indexOf(" ");
LinkAlone = LinkPiece.substring(0,lienfin);
chatStringRightPiece = chatsendvar.substring(((lienfin + linkLocation)),chatsendvar.length) ;
console.log( chatStringLeftPiece + " droit et gauche " + chatStringRightPiece + " number of theloop in the while=" + increment);
LinktagString = "<a target='_blank' href='http://"+ LinkAlone+"'>"+LinkAlone+"</a>";
chatsendvar = chatStringLeftPiece + " " + chatStringRightPiece;
linkTagA.push(LinktagString);
variablelocation.push(chatStringLeftPiece.length + earlierLinkLength);
earlierLinkLength = earlierLinkLength + LinktagString.length +1;
}
linkLocation = chatsendvar.indexOf("www.");
}
for (var x = 0, j = linkTagA.length; x<j; x++) {
chatsendvar = chatsendvar.split('');
chatsendvar.splice((variablelocation[x]),1," "+linkTagA[x]+" ");
chatsendvar = chatsendvar.join('');
};
return chatsendvar;
}
All this code to detect links in a text?
I know that's not what you asked, but this small function can do this. It can detect links beginning with www. or http:// and even handles url parameters, like ?a=1&b=2. Here is a demo fiddle.
The regex could be modified to handle https:// or url encoding for example, but you get my point.
function makeLinks(text) {
return text.replace(/(?:http:\/\/|(www\.))([\w\d.\/\?&=]+)/gi, '<a target="_blank" href="http://$1$2">$1$2</a>');
}
I have this js code
window.addEvent("domready", function () {
var maxLength = 700;
var counterFluid = 1;
var wallFluid = new Wall("wall", {
"width":180,
"height":180,
"rangex":[-14,21],
"rangey":[-8,12],
callOnUpdate: function (items) {
items.each(function (e, i) {
var a = new Element("img[src=images/"+counterFluid+".jpg]");
counterFluid++;
if( counterFluid > maxLength ) counterFluid = 1;
});
}
});
wallFluid.initWall();
});
This results in displaying images in an array. Now I would like to add links to images such that when the image is clicked it opens a new page.
I tried this code
a.onclick = function () {
window.location.href = '/"+counterFluid+".html';
};
A new page is opening but the url just shows as /"+counterFluid+".html
I know that this is not correct. Kindly help. The URL for each image will be different so trying to use +counterFluid+
Thank You
window.location.href = "/" + counterFluid + ".html";
Try it like this with only ".
You could use the id attribute of the image to store the 'counterFluid' var like this:
var img = document.createElement('img');
img.setAttribute('id', counterFluid);
img.setAttribute('src', 'images/' + counterFluid + '.jpg');
img.onclick = function() {
window.location.href = '/' + this.id + '.html';
}
Suppose my html is
One
Two
and Js is
$(window).on("hashchange"){
alert(document.location.hash);
}
I want to get the hash value which was before hash change .Is it Possible?If yes ,How?
use that
$(window).on("hashchange", function(e){
console.log(e.originalEvent.oldURL)
console.log(e.originalEvent.newURL)
});
Demo: http://jsbin.com/ulumil/
You have to track the last hash, for example:
var currentHash = function() {
return location.hash.replace(/^#/, '')
}
var last_hash
var hash = currentHash()
$(window).bind('hashchange', function(event){
last_hash = hash
hash = currentHash()
console.log('hash changed from ' + last_hash + ' to ' + hash)
});
Actually the solution provided by Amit works but with jquery library and crossplatform as well.
Here is a more simplified solution using core javascript and crossbrowser as well. (checked with latest version of IE/FF/Chrome/Safari)
window.onhashchange = function(e){
console.log(e);
var oldURL = e.oldURL;
var newURL = e.newURL;
console.log("old url = " + oldURL);
console.log("new url = " + newURL);
var oldHash = oldURL.split("#")[1];
var newHash = newURL.split("#")[1];
console.log(oldHash);
console.log(newHash);
};
Don't use
$(window).on("hashchange", function(e){
console.log(e.originalEvent.oldURL)
console.log(e.originalEvent.newURL)
});
It won't work on IE and probably elsewhere too.
Use this rather.
(function(w, $){
var UrlHashMonitor = {};
UrlHashMonitor.oldHash = '';
UrlHashMonitor.newHash = '';
UrlHashMonitor.oldHref = '';
UrlHashMonitor.newHref = '';
UrlHashMonitor.onHashChange = function(f){
$(window).on('hashchange', function(e){
UrlHashMonitor.oldHash = UrlHashMonitor.newHash;
UrlHashMonitor.newHash = w.location.hash;
UrlHashMonitor.oldHref = UrlHashMonitor.newHref;
UrlHashMonitor.newHref = w.location.href;
f(e);
});
};
UrlHashMonitor.init = function(){
UrlHashMonitor.oldHash = UrlHashMonitor.newHash = w.location.hash;
UrlHashMonitor.oldHref = UrlHashMonitor.newHref = w.location.href;
};
w.UrlHashMonitor = UrlHashMonitor;
return UrlHashMonitor;
})(window, window.jQuery);
/*
* USAGE EXAMPLE
*/
UrlHashMonitor.init();
UrlHashMonitor.onHashChange(function(){
console.log('oldHash: ' + UrlHashMonitor.oldHash);
console.log('newHash: ' + UrlHashMonitor.newHash);
console.log('oldHref: ' + UrlHashMonitor.oldHref);
console.log('newHref: ' + UrlHashMonitor.newHref);
//do other stuff
});
This should work in all modern browsers.
DEMO: https://output.jsbin.com/qafupu#one