I am trying to use this code from here: http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/#test4
Html:
<script>
$(function(){
// Bind an event to window.onhashchange that, when the hash changes, gets the
// hash and adds the class "selected" to any matching nav link.
$(window).hashchange( function(){
var hash = location.hash;
// Set the page title based on the hash.
document.title = '13213';
$('title').text("Boo");
// Iterate over all nav links, setting the "selected" class as-appropriate.
$('#nav a').each(function(){
var that = $(this);
that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
document.title = '13213';
$(this).attr("title", "asdsad");
});
})
// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
$(window).hashchange();
});
</script>
test 1
test 2
test 3
test 4
Can someone explain why document.title = '13213'; doesn't not work for me ? It does't change the documents title on click.
I tried using $('title').text("13213") including jQuery and didn't work either. I have no idea why.
Edit: I changed my code to be identical with the http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/#test4 website where i got the code from.
Both
document.title = '13213';
$('title').text("13213")
must work fine.
Notice that
$(this).attr("title", "asdsad");
set title attr for A element
The problem is you not call function in closure.
Change
$(function(){ -> (function(){
and
}); -> })()
And everything will work
Related
I have a select with options that have values that are populated with jQuery based on data attributes from divs. When a user select an option, the div with the data attribute that matches the value of the option is displayed. Now I'm trying to create a deep linking option, so when I have a url like https://my-site.com/page/#option-2 the option-2 is preselected in the select and the div with data attribute option-2 is displayed. So far I have this javascript:
$(window).on('load', function() {
let urlHash = window.location.hash.replace('#','');
console.log(urlHash);
if ( urlHash ) {
$('.dropdown').val(urlHash);
$('body').find('.location').removeClass('is-active');
$('body').find(`.location[data-location-hash=${urlHash}]`).addClass('is-active');
}
});
If I enter the url https://my-site.com/page/#option-2 the site goes in infinite loop and never loads without displaying any error in the console.. If I refresh the page while loading, the console.log is displayed with the correct string that I'm expecting, but the .location[data-location-hash=option-2] is not displayed and the option is not selected... I'm using the same code for the change function of the dropdown and is working, but it's not working in the load function.. Is there anything I'm missing?
JSFiddle, if it's of any help:
https://jsfiddle.net/tsvetkokrastev/b0epz1mL/4/
Your site is looping because you are doing a window.location.replace To get the urlHash you should use
$(window).on('load', function() {
var href = location.href; // get the url
var split = href.split("#"); // split the string
let urlHash = split[1]; // get the value after the hash
if ( urlHash ) {
$('.dropdown').val(urlHash);
$('body').find('.location').removeClass('is-active');
$('body').find('.location[data-location-hash='+urlHash+']').addClass('is-active');
}
});
https://codepen.io/darkinfore/pen/MWXWEvM?editors=1111#europe
Solved it by using a function instead of $(window).on('load').. Also added $( window ).on( 'hashchange', function( ) {}); to assure that the js will run again after the hash is changed.
Here is an updated jsfiddle: https://jsfiddle.net/tsvetkokrastev/b0epz1mL/5/
in a current project i have different articles containing different headings (<h3>). Because the articles are composed in a CMS we cannot set the id of the <h3> element from the beginning on. Thats why I'm setting them on page load:
$(document).ready(function(){
let articleContent = $(".article-body")
let headings = articleContent.find("h3")
headings.each(function() {
$(this).attr("id", $(this).first().text().replace(/\s/g, "-"))
}
}
The problem is, when I try top open the URL with the given id of the heading as its hash to navigate the user to the right heading (eg. https://test.com/article-122321#heading2), this is not working. I guess this is the case because on page load the headings do not have any ids set and the browser doesn't know where to navigate to.
Can you help out with a solution for that? Do I have to set the ids at another point of time or do I need some custom Javascript code to tell the browser to navigate to the heading?
Thanks!
Have a try of this
$(document).ready(function() {
$(".article-body h3").each(function() {
$(this).attr("id", $(this).first().text().replace(/\s/g, "-"))
})
const hash = location.hash;
const $element = hash ? $(hash) || null; // assuming a valid selector in the hash
if ($element) $element[0].scrollIntoView({ // use the DOM method
behavior: "smooth", // or "auto" or "instant"
block: "start" // or "end"
});
});
Сan you explain please.
Why returned, only the first data attribute - "link-1.html", even if I click on the second link
<a class="project-link" href="link-1.html" data-url="link-1.html">
<a class="project-link" href="link-2.html" data-url="link-2.html">
var toUrl = $('.project-link').attr('data-url');
$('a').click(function() {
window.location.hash = toUrl;
});
The meaning of such action - my links open through Ajax, but I want to URL displayed in the browser.
I want to make it as behance, if you click on the cards portfolio, they displayed through Ajax in the same window, but it also left open the possibility of direct appeal to the links. That's why I want to URL displayed in the browser address bar
You have to get current target url by this
$('a').click(function() {
var toUrl = $(this).data('url'); // use this as current target
window.location.hash = toUrl;
});
I recommend you to use .data() when you're retrieving data attributes (only) instead of .attr()
Demo
.attr( attributeName )
Returns: String
Description: Get the value
of an attribute for the first element in the set of matched elements.
$('.project-link') matches more than one element. Therefore, $('.project-link').attr('data-url') will return the value of the data-url attribute for the first element in the set.
To solve this you have maintain the context of the clicked element as you get the attribute, and you do this by using the this keyword.
And if you have other event listeners attached to the element already and you do not want them to fire -- although ajax calls will abort when the user is redirected -- you can use event.stopImmediatePropagation():
$('a').on('click', function( event ) {
event.stopImmediatePropagation();
window.location.hash = $(this).data('url'); //this here refers to the element that was clicked.
});
$('a[data-url]').click(function() {
window.location.href = $(this).data("url");
});
You might want to try this:
$('.project-link').click(function(){
window.location.hash = $(this).data('url');
});
I'm trying to click on a logout button, which I have retrieved from the current page. I successfully got the id of the logout link. But when I click on it, an error occurs
Cannot dispatch mousedown event on nonexistent selector
function getLogoutId()
{
var logoutid = "";
$(document).find("a").each(function(key,value){
var id = $(this).attr("id");
if(id.toLowerCase().indexOf("logout") > -1)
{
__utils__.echo("insidelogout" + id);
logoutid = id;
}
});
return logoutid;
}
var logoutid = this.evaluate(getLogoutId);
fs.write("logout.txt", this.getHTML(), 'w');
this.thenClick("#"+logoutid, function(){});
I have written the html content to a file, in which I checked for the id and it is there. The id attribute in question looks like this:
et-ef-content-ftf-flowHeader-logoutAction
I see nothing wrong with your code aside from strange usage of jQuery.
You can try other CSS selectors for clicking:
casper.thenClick("[id*='logout']"); // anywhere
or
casper.thenClick("[id$='logoutAction']"); // ending
or
casper.thenClick("[id|='logoutAction']"); // dash-separated
Maybe it is an issue with the code that follows the shown code. You can try to change thenClick to click.
Have you tried using just this.click("#"+logoutid);?
Also have you considered using jQuery to click on the button? Something like this...(first make a variable of your id so you can pass into jQuery).
var id = "#"+logoutid;
this.evaluate(function(id){
jQuery(id).click();
},id);
Using ratchet framework, I am able to slidein/slideout of any pages, I arrive on a situation where I have to get the data first before it slides to the next page. I can get the data but the slide transition of the page is gone. Is there a way to do this?
I have this example anchor here:
Next link
tried using,
$('a').each(function() {
`var $this = $(this);`
`$this.attr('data-ignore', 'push');`
`$this.click(function(e) {`
`e.stopPropagation();`
`//... get the data here $this.attr('data-want')`
`$this.attr('data-ignore', '');`
`});`
});
use .data() instead:
$this.data('ignore', 'push');
and to set it empty
$this.data('ignore', '');
This is what I use, the advantage of "on" is that it will work whenever an a tag is appended to the page.
You can remove the if statement if you want to, I'm using PhoneGap so this gets around some issues for me.
$(document.body).on('click', 'a', function(e){
$(this).attr('data-ignore', 'push'); //disables ratchet push.js for now!
var url = $(this).attr('href');
if (url && url.indexOf('http') == -1) {
location.href = url;
}
});