Change url using jquery - javascript

С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');
});

Related

Link that preselect dropdown option with jQuery

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/

Inject GET parameter to target URL of a button, on click

I have multiple buttons with the class myButton. Each button has a value which is send to a server on click. The target URL of the button does look like this:
http://mysite/test/test.html?cid=15
After I click on the button, the following GET parameter should be added to the URL and then the button should be submitted:
mySessionVar=1
So the new URL should look like this:
http://mysite/test/test.html?cHash=d009eb3f9f4e1020435b96a8f7251ad5&mySessionVar=1
Why I have to inject it?
I am working with fluid. AFAIK it is not possible to manipulate fluid tags with JavaScript. However, I need to add a sessionStorage item value to the fluid tags arguments attribute.
My fluid code:
<f:link.action controller="Download" action="download" arguments="{cid: category.uid}" class="myButton">Download</f:link.action>
So my attempt is to append my sessionStorage item as GET parameter to the target URL of the button and then send it, e.g.:
$(".myButton").on
(
"click",
function(event)
{
//First prevent the default event
event.preventDefault();
...inject the sessionStorage item as GET parameter to the target URL of the button, then do whatever the button would do normally...
//Go to new URL
window.location.replace(NEW URL);
}
);
Is this possible?
EDIT: This is how the rendered HTML of the buttons looks like:
<a class="myButton" href="/de/mysite/test/test.html?tx_mydownloads_myfilelist%5Bcid%5D=15&&tx_mydownloads_myfilelist%5Baction%5D=download&tx_mydownloads_myfilelist%5Bcontroller%5D=Download&cHash=d009eb3f9f4e1020435b96a8f7150ad5">Download</a>
EDIT: I have another idea, maybe I could just read the target URL somehow, then add my new GET param to it and then load that URL with window.location.replace?
You can indeed just use the href from the button and use it to feed window.location.href, like so:
$('.myButton').on('click', function(e) {
e.preventDefault();
var href = $(this).attr('href'),
queryString = 'mySessionVar='+sessionStorage.getItem("myItem"),
newHref;
if (href.indexOf('?') !== -1) {
newHref = href + '&' + queryString;
} else {
newHref = href + '?' + queryString;
}
window.location.href = newHref;
});
This also handles the case when there is no previous query string present on the link and appends it with ? instead of &, but that part can be omitted if that won't happen in your app.
The following snippet should be enough to add your mySessionVar=1 parameter to the href attribute:
$('.myButton').on('click', function(e) {
$(this).attr('href', $(this).attr('href') + "&mySessionVar="+ sessionStorage.getItem('myVar');
});
You don't have to prevent the default, because your click handler function is called before the default event handler (who does roughly speaking: read the href attribute and load it).
You can use .serialize function in jquery which is simple and modern function to get all the selected buttons/filters into a url param format with amberson simple. I can't explain more clear than what is said in Jquery website. Please refer the link below to find how to use the function. https://api.jquery.com/serialize/#serialize

Html change document's title

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

Trying To Add Onclick To Links, But Can't With .onclick

So I'm trying to use ajax to put content into a div, and trying to have it change all internal links before it adds the content so that they will use the funciton and load with ajax instead of navigating to another page. My function is supposed to get the data with ajax, change the href and onclick attributes of the link, then put it into the div... However, all it's doing is changing the href and not adding an onclick attribute at all. Here's what I was using so far:
function loadHTML(url, destination) {
$.get(url, function(data){
html = $(data);
$('a', html).each(function(){
if ( $.isUrlInternal( this.href )){
this.onclick = loadHTML(this.href,"forum_frame"); // I've tried using both a string and just putting the function here, neither seem to work.
this.href = "javascript:void(0)";
}
});
$(destination).html(html);
});
};
Also, I'm using jquery-urlinternal. Just thought that was relevant.
You can get the effect you want with less effort by doing this on your destination element ahead of time:
$(destination).on("click", "A", function(e) {
if ($.isUrlInternal(this.href)) {
e.preventDefault();
loadHTML(this.href, "forum_frame");
}
});
Now any <a> that ends up inside the destination container will be handled automatically, even content added in the future by DOM manipulations.
When setting a function to onclick through js it will not show on the markup as an attribute. However in this case it is not working because the function is not being set correctly. Easy approach to make it work,
....
var theHref=this.href;
this.onclick = function(){loadHTML(theHref,"forum_frame");}
....
simple demo http://jsbin.com/culoviro/1/edit

Load Html Content if not exist JQuery AJAX

I have a page with 3 buttons. >Logos >Banners >Footer
When any of these 3 buttons clicked it does jquery post to a page which returns HTML content in response and I set innerhtml of a div from that returned content . I want to do this so that If I clicked Logo and than went to Banner and come back on Logo it should not request for content again as its already loaded when clicked 1st time.
Thanks .
Sounds like to be the perfect candidate for .one()
$(".someItem").one("click", function(){
//do your post and load the html
});
Using one will allow for the event handler to trigger once per element.
In the logic of the click handler, look for the content having been loaded. One way would be to see if you can find a particular element that comes in with the content.
Another would be to set a data- attribute on the elements with the click handler and look for the value of that attribute.
For example:
$(".myElements").click(function() {
if ($(this).attr("data-loaded") == false {
// TODO: Do ajax load
// Flag the elements so we don't load again
$(".myElements").attr("data-loaded", true);
}
});
The benefit of storing the state in the data- attribute is that you don't have to use global variables and the data is stored within the DOM, rather than only in javascript. You can also use this to control script behavior with the HTML output by the server if you have a dynamic page.
try this:
HTML:
logos<br />
banner<br />
footer<br />
<div id="container"></div>
JS:
$(".menu").bind("click", function(event) {
event.stopPropagation();
var
data = $(this).attr("data");
type = $(this).attr("type");
if ($("#container").find(".logos").length > 0 && data == "logos") {
$("#container").find(".logos").show();
return false;
}
var htmlappend = $("<div></div>")
.addClass(type)
.addClass(data);
$("#container").find(".remover-class").remove();
$("#container").find(".hidde-class").hide();
$("#container").append(htmlappend);
$("#container").find("." + data).load("file_" + data + "_.html");
return false;
});
I would unbind the click event when clicked to prevent further load requests
$('#button').click(function(e) {
e.preventDefault();
$('#button').unbind('click');
$('#result').load('ajax/test.html ' + 'someid', function() {
//load callback
});
});
or use one.click which is a better answer than this :)
You could dump the returned html into a variable and then check if the variable is null before doing another ajax call
var logos = null;
var banners = null;
var footer = null;
$(".logos").click(function(){
if (logos == null) // do ajax and save to logos variable
else $("div").html(logos)
});
Mark nailed it .one() will save extra line of codes and many checks hassle. I used it in a similar case. An optimized way to call that if they are wrapped in a parent container which I highly suggest will be:
$('#id_of_parent_container').find('button').one("click", function () {
//get the id of the button that was clicked and do the ajax load accordingly
});

Categories

Resources