Click event only works on second post - javascript

The below function works only after the page has been refreshed. When the page is refreshed again afterwards it stops working again and so on.
<button id="moreBtn" type="button" class="archive btn btn-default col-sm-12"></button>
function ShowHideBtn() {
var newss = 5;
var numItems = $(".news").length;
hidenews = "- Show Less Products";
shownews = "+ Show More Products";
$(".news:not(:lt(" + newss + "))").hide();
$("hr:not(:lt(" + newss + "))").hide();
if (numItems >= newss) {
$(".archive").show();
$(".archive").html(shownews);
$(".archive").on("click", function (e) {
e.preventDefault();
if ($(".news:eq(" + newss + ")").is(":hidden")) {
$("hr:hidden").show();
$(".news:hidden").show();
$(".archive").html( hidenews );
} else {
$("hr:not(:lt(" + newss + "))").hide();
$(".news:not(:lt(" + newss + "))").hide();
$(".archive").html(shownews);
}
return false;
});
} else {
$(".archive").hide();
}
}
Thanks in advance

This is a guess as there is insufficient information to confirm it. Please provide the full page HTML/code:
As browser page requests are stateless (so it can't know it is every other load), this sounds like a timing issue. The HTML would generally load slower the first time, so if the JS code is not positioned after the element it references (or is inside a DOM ready handler), then it may fail to find the .archive element. It is more likely random than "every other page load" though if it is a timing issue.
Try one of the following:
Place your JS code (or JS script include) after the element they reference. Just before the closing </body> tag is typical for this option.
Place your code inside a DOM ready handler, then its position does not matter. e.g. like:
$(document).ready(function(){
// Your code here
});
or the short-cut version of DOM ready:
$(function(){
// Your code here
});

Related

Click on a button until it disappears in CasperJS

I have this sample of my code:
function clickOldShares() {
console.log("Waiting for all shares");
element = document.querySelector("#pagelet_scrolling_pager > div > div > a");
return element;
}
casper.thenOpen("https://www.facebook.com/shares/view?id=" + fb_objectID,function(){
console.log("Open post with object-id");
});
casper.then(function(){
element = this.evaluate(clickOldShares);
});
casper.wait(2000,function() {
console.log('ELEMENT1: ' + element);
element = this.evaluate(clickOldShares);
});
casper.wait(2000,function() {
newelement = this.evaluate(clickOldShares);
console.log('ELEMENT2: ' + newelement);
});
casper.wait(2000,function() {
newelement = this.evaluate(clickOldShares);
console.log('ELEMENT3: ' + newelement);
});
I´m not understanding how can I transform this calls to clickOldShares in a loop using CasperJS because casper.wait is asynchronous. May I have some example of how to do this, please?
The page doesn't load all data in one time. It's necessary to click on the 'Older Shares' button until the data appears. And this can happen many times, depending the amount of data. So, I need to click as often as needed before capturing data.
First thing's first, you can't use clickOldShares for anything as it is now. casper.evaluate() provides access to the DOM, but the passed in function is sandboxed and executed in the page context. All data must be explicitly passed in and out, and this has to be primitive. DOM elements are not primitive and cannot be passed out of the page context (this.evaluate(clickOldShares) will always return null). You will either have to call the click code inside of the page context.
You can wait for an element to appear with waitForSelector. You really don't need to iterate to wait for it.
var selector = "#pagelet_scrolling_pager > div > div > a";
casper.start()
.thenOpen(url)
.waitForSelector(selector, null, null, 15000); // max 15 seconds
.then(function(){
this.capture("screen1.png");
this.click(selector);
})
.then(function(){
this.capture("screen2.png");
})
.run();
The third argument for waitForSelector is the callback for when the timeout is reached, but the element is not found. The fourth argument is a custom timeout. The default timeout is set to 10 seconds.
It seems you need to click on a certain selector until it disappears. You can't use a loop for this, because the functions are asynchronous. You will have to use recursion like this:
var selector = "#pagelet_scrolling_pager > div > div > a";
var i = 0;
function step() {
if (this.exists(selector)) {
this.capture("screen"+(i++)+".png");
this.click(selector);
this.wait(2000, step);
} else {
this.capture("screen_final.png");
}
}
casper.start()
.thenOpen(url)
.then(step)
.then(function(){
// TODO: do something else
})
.run()

Javascript not being called after loading

I have a few javascript routines that I need to run with my application. When I run the application and go to view source, I see the javascript file import, and when I click on it, I am taken to the javascript file, so I know it is being brought down to the client. Right now, I have a simple alert in the beginning of the method I am calling, but that isn't even happening, so I'm not sure what's going on.
Does this look like the correct way to call the javascript when the button is clicked?
<p><input type="button" value="Add File" onclick="go();" /></p>
Here is the javascript file:
var typeAId= 0;
var typeBId= 0;
function addNewDocument(parentId, elementTag, elementId, html) {
// Adds an element to the document
var p = document.getElementById(parentId);
var newElement = document.createElement(elementTag);
newElement.setAttribute('id', elementId);
newElement.innerHTML = html;
p.appendChild(newElement);
}
function go(){
alert('ok');
}
function removeElement(elementId) {
// Removes an element from the document
var element = document.getElementById(elementId);
element.parentNode.removeChild(element);
}
function addNewDocument(input) {
var fileToRemove = 'file-';
alert('ok');
var elementName = null;
if(input === 'formAInput'){
elementName = 'formA[]';
typeAId++;
fileToRemove = fileToRemove+typeAId;
} else {
elementName = 'formB[]';
typeBId++;
fileToRemove = fileToRemove+typeBId;
}
var html = '<input type="file" name="'+elementName+'" /> ' +
'Remove';
if(input === 'formAInput'){}
addElement('typeAFilesDiv', 'p', 'file-' + typeAId, html);
} else {
addElement('typeBFilesDiv', 'p', 'file-' + typeBId, html);
}
alert('end');
}
Here is how I am importing the javascript:
<script src="/js/myJS.js"></script>
The js directory is located under the 'war' directory in my Google App Engine Project.
When I click the button, I do not see an alert.
Additional documentation, code, and screenshots would help the community answer more holistically. However, to answer your most basic question, yes, that is the correct way to use the onclick attribute.
I hypothesize that the JavaScript addFile function is not doing what you want it to or something is wrong with the document.ready event.

Ubuntu HTML5 App: Change Tab on JS command

First Question here, too! Yay! Just moved this from AskUbuntu.
I am just about to finish a little private project for gaining some experience where i try to change the app layout so it works as a normal website (on Jimdo, so it was quite of a challenge first) without much JavaScript required but is fully functional on mobile view.
Since Jimdo serves naturally only the actual site, I had to implement an
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
redirect into the __doSelectTab() function in tabs.js . (In js I took the values from the jimdo menu string to build the TABS menu with this link attribute)
Now everything works fine exept at page load the first tab is selected. I got it to set the .active and .inactive classes right easily, but it is not shifted to the left.
So my next idea is to let it initialize as always and then send a command to change to the current tab.
Do you have any idea how to manage this? I couldn't because of the this.thisandthat element I apparently don't really understand...
Most of you answering have the toolkit and the whole code, but I am listing the select function part of the tabs.js:
__doSelectTab: function(tabElement, forcedSelection) {
if ( ! tabElement)
return;
if (tabElement.getAttribute("data-role") !== 'tabitem')
return;
if (forcedSelection ||
(Array.prototype.slice.call(tabElement.classList)).indexOf('inactive') > -1) {
window.clearTimeout(t2);
activeTab = this._tabs.querySelector('[data-role="tabitem"].active');
offsetX = this.offsetLeft;
this._tabs.style['-webkit-transition-duration'] = '.3s';
this._tabs.style.webkitTransform = 'translate3d(-' + offsetX + 'px,0,0)';
this.__updateActiveTab(tabElement, activeTab);
if (activeTab.getAttribute('jimdo-target') != null)
location.href = activeTab.getAttribute('jimdo-target');
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (e) {
e.classList.remove('inactive');
});
var targetPageId = tabElement.getAttribute('data-page');
this.activate(targetPageId);
this.__dispatchTabChangedEvent(targetPageId);
} else {
[].forEach.call(this._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)'), function (el) {
el.classList.toggle('inactive');
});
var self = this;
t2 = window.setTimeout(function () {
var nonActiveTabs = self._tabs.querySelectorAll('[data-role="tabitem"]:not(.active)');
[].forEach.call(nonActiveTabs, function (el) {
el.classList.toggle('inactive');
});
}, 3000);
}
},
...and my app.js hasn't anything special:
var UI = new UbuntuUI();
document.addEventListener('deviceready', function() { console.log('device ready') }, true);
$(document).ready(function () {
recreate_jimdo_nav();
UI.init();
});
So meanwhile found a simple workaround, however I'd still like to know if there is another way. Eventually I noticed the __doSelectTab() function is the one that executes the click, so it does nothing but to show the other tab names when they are hidden first. so I added the global value
var jnavinitialized = false;
at the beginning of the tabs.js and run
var t = this;
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 0);
setTimeout(function(){t.__doSelectTab(t._tabs.querySelector('[data-role="tabitem"].jnav-current'))}, 1);
setTimeout(function(){jnavinitialized = true;}, 10);
at the top of the __setupInitialTabVisibility() function. Then I changed the location.href command to
if (activeTab.getAttribute('jimdo-target') != null && jnavinitialized)
location.href = activeTab.getAttribute('jimdo-target');
And it works. But originally I searched for a way to change the tab on command, not to run the command for selecting twice. So if you know a better or cleaner way, you are welcome!

Click all anchor tags on page with given class, but cancel prior to navigation

Trying to automate some testing for some analytics tracking code, and I'm running into issues when I try passing links into the each() method.
I copied a lot of this from stackoverflow - how to follow all links in casperjs, but I don't need return the href of the link; I need to return the link itself (so I can click it). I keep getting this error: each() only works with arrays. Am I not returning an array?
UPDATE:
For each anchor tag that has .myClass, click it, then return requested parameters from casper.options.onResourceReceived e.g. event category, event action, etc. I may or may not have to cancel the navigation the happens after the click; I simply only need to review the request, and do not need the follow page to load.
Testing steps:
click link that has .myClass
look at request parameters
cancel the click to prevent it from going to the next page.
I'm new to javascript and casper.js, so I apologize if I'm misinterpreting.
ANOTHER UPDATE:
I've updated the code to instead return an array of classes. There are a few sketchy bits of code in this though (see comments inline).
However, I'm now having issues canceling the navigation after the click. .Clear() canceled all js. Anyway to prevent default action happening after click? Like e.preventDefault();?
var casper = require('casper').create({
verbose: true,
logLevel: 'debug'
});
casper.options.onResourceReceived = function(arg1, response) {
if (response.url.indexOf('t=event') > -1) {
var query = decodeURI(response.url);
var data = query.split('&');
var result = {};
for (var i = 0; i < data.length; i++) {
var item = data[i].split('=');
result[item[0]] = item[1];
}
console.log('EVENT CATEGORY = ' + result.ec + '\n' +
'EVENT ACTION = ' + result.ea + '\n' +
'EVENT LABEL = ' + decodeURIComponent(result.el) + '\n' +
'REQUEST STATUS = ' + response.status
);
}
};
var links;
//var myClass = '.myClass';
casper.start('http://www.leupold.com', function getLinks() {
links = this.evaluate(function() {
var links = document.querySelectorAll('.myClass');
// having issues when I attempted to pass in myClass var.
links = Array.prototype.map.call(links, function(link) {
// seems like a sketchy way to get a class. what happens if there are multiple classes?
return link.getAttribute('class');
});
return links;
});
});
casper.waitForSelector('.myClass', function() {
this.echo('selector is here');
//this.echo(this.getCurrentUrl());
//this.echo(JSON.stringify(links));
this.each(links, function(self, link) {
self.echo('this is a class : ' + link);
// again this is horrible
self.click('.' + link);
});
});
casper.run(function() {
this.exit();
});
There are two problems that you're dealing with.
1. Select elements based on class
Usually a class is used multiple times. So when you first select elements based on this class, you will get elements that have that class, but it is not guaranteed that this will be unique. See for example this selection of element that you may select by .myClass:
myClass
myClass myClass2
myClass myClass3
myClass
myClass myClass3
When you later iterate over those class names, you've got a problem, because 4 and 5 can never be clicked using casper.click("." + links[i].replace(" ", ".")) (you need to additionally replace spaces with dots). casper.click only clicks the first occurrence of the specific selector. That is why I used createXPathFromElement taken from stijn de ryck to find the unique XPath expression for every element inside the page context.
You can then click the correct element via the unique XPath like this
casper.click(x(xpathFromPageContext[i]));
2. Cancelling navigation
This may depend on what your page actually is.
Note: I use the casper.test property which is the Tester module. You get access to it by invoking casper like this: casperjs test script.js.
Note: There is also the casper.waitForResource function. Have a look at it.
2.1 Web 1.0
When a click means a new page will be loaded, you may add an event handler to the page.resource.requested event. You can then abort() the request without resetting the page back to the startURL.
var resourceAborted = false;
casper.on('page.resource.requested', function(requestData, request){
if (requestData.url.match(/someURLMatching/)) {
// you can also check requestData.headers which is an array of objects:
// [{name: "header name", value: "some value"}]
casper.test.pass("resource passed");
} else {
casper.test.fail("resource failed");
}
if (requestData.url != startURL) {
request.abort();
}
resourceAborted = true;
});
and in the test flow:
casper.each(links, function(self, link){
self.thenClick(x(link));
self.waitFor(function check(){
return resourceAborted;
});
self.then(function(){
resourceAborted = false; // reset state
});
});
2.2 Single page application
There may be so many event handlers attached, that it is quite hard to prevent them all. An easier way (at least for me) is to
get all the unique element paths,
iterate over the list and do every time the following:
Open the original page again (basically a reset for every link)
do the click on the current XPath
This is basically what I do in this answer.
Since single page apps don't load pages. The navigation.requested and page.resource.requested will not be triggered. You need the resource.requested event if you want to check some API call:
var clickPassed = -1;
casper.on('resource.requested', function(requestData, request){
if (requestData.url.match(/someURLMatching/)) {
// you can also check requestData.headers which is an array of objects:
// [{name: "header name", value: "some value"}]
clickPassed = true;
} else {
clickPassed = false;
}
});
and in the test flow:
casper.each(links, function(self, link){
self.thenOpen(startURL);
self.thenClick(x(link));
self.waitFor(function check(){
return clickPassed !== -1;
}, function then(){
casper.test.assert(clickPassed);
clickPassed = -1;
}, function onTimeout(){
casper.test.fail("Resource timeout");
});
});

How to use onhashchange with dynamic items

So, I have two select boxes on a webpage, but in different anchors (one on the page, the other in an iframe) and I'm trying to get the code to detect which anchor it's in, and then relay the selected value in that box to a link. Here's my code:
function locationHashChanged() {
if (location.hash === "#player") {
function setText(text) {
var selectVal = text;
var url = $('twitter').attr("href");
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}
}
if (location.hash === "#embeds") {
$(function () {
var $twitter = $('twitter');
$('#iframe').on('load', function () {
$(this).contents().find('#cds').change(function () {
var selectVal = $(this).val() || 'nothing much';
url = 'https://twitter.com/intent/tweet?button_hashtag=stream&text=Just enjoying ' + selectVal + ' on';
$('#twitter').attr("href", url);
}).change();
});
});
}
}
I know this is probably not right, or anywhere near right, but am I on the right track? I'm honestly a complete noob when it comes to javascript. Thanks in advance
Apart from what exactly your function looks like, it's not executed on hash change right now.
You use jQuery, so you can listen for hash change like this:
$(window).on('hashchange', function() {
// your locationHashChanged() function goes here
});
With this, every time the hash changes your function will be executed. The very base of your code is alright:
if (location.hash === "#player") {
// this is executed if hash changed to #player
}
if (location.hash === "#embeds") {
// this is executed if hash changed to #embeds
}
Although, inside your if blocks you declare functions (which doesn't make much sense here).
Also note that if the iframe is not from your domain, you won't be able to get any data from it. If that's the case, read more about same origin policy.

Categories