How to change the function handlers for a link in Jquery? - javascript

So in a particular page I serve a lot of content. Now user can click on the bookmark button for a piece of content and it should call the bookmark function which communicates necessary information to the server. Next time when the user clicks on the link it should call the unbookmark function which does the converse of what bookmark function does and the next time the user clicks on this link, it should call the bookmark function. Flip flop flip flop....
My link for the bookmark button kinda looks like this.
<a id = cno class = 'bookmark_button'></a>
I did come up with a solution for this by counting clicks for a particular cno using a global array. This is a very inconvenient thing cause the user has the option to refresh content in which case I have to reset all the counters! So I was wondering if there was an elegant solution to this. So that I could change the click event handler on the fly.
Edit:
Bookmark function code:
function bookmark(cno){
result = server_comm('bookmark', cno);
if(success){
//change the icon of the bookmark button;
}
else{
// display error
}
}

Your server should render links depend on the bookmark state like below.
HTML
<!-- a bookmarked link looks like this -->
<a id="cno" class="bookmark_button bookmarked"></a>
<!-- a new link looks like this -->
<a id="cno" class="bookmark_button"></a>
Javascript
jQuery(function($) {
$(".bookbmark_button").click(function() {
var btn = $(this);
if(btn.is(".bookmarked")) {
btn.removeClass('bookmarked');
// call undo bookmark here
} else {
btn.addClass('bookmarked')
// call do bookmark here
}
});
});

Make an AJAX call to the server, and keep the state (on/off states of the book marks) at the server. Of course this will increase the communication with your server more but it will be more reliable.
__update__
Whenever someone clicks on a book mark button, make an AJAX call to the server. Server should get the request and decide what to do (add a new book mark or delete it) and it should respond accordingly. Depending on the answer from the server, you can decorate your button.
To do so,
function onNewBookMarkCallBack(){
$('#idOfTheItemThatYouWantToChangeTheClass').addClass("newBookMark");
}
function onBookMarkDeletedCallBack(){
$('#idOfTheItemThatYouWantToChangeTheClass').removeClass("newBookMark");
}

See the following fiddle:
http://jsfiddle.net/mdfb1ef6/12/
var firstClick = function()
{
$(this).text("Click me again!")
$(this).one("click", secondClick);
}
var secondClick = function()
{
$(this).text("Click me!");
$(this).one("click", firstClick);
}
$("a").one("click", firstClick);
Essentially, you just call the one method again on the element, passing in a new handler.

You can save the state of "checked/unchecked" on the A tag eg.:
<a id="bookmark-toggle" class="xpto bookmark-unchecked" >bookmark icon</a>
<script>
$("#bookmark-toggle").click(function(){
if ( $(this).hasClass("bookmark-unchecked") ) {
// here you execute code that ADD text on bookmark
// two lines below you can also run just inside a ajax callback function, so you can run it just if server said it could insert bookmark with success, and if not success, does not run two lines below and tell user what happens
$(this).removeClass("bookmark-unchecked")
$(this).addClass("bookmark-checked")
} else if ( $(this).hasClass("bookmark-checked") ) {
// here you execute code that REMOVE text on bookmark
$(this).removeClass("bookmark-checked")
$(this).addClass("bookmark-unchecked")
}
});
</script>
Plus: to work alternating between two class, give to you the ability to alternate button style too. you can set an icon different to both cases, or even alternating text too.. you choose..

Related

Href link that redirects to another page has a specific action

On my site I created several href buttons, I want these different buttons to lead to the same page but with an additional js action.
As when I click on the first link, this brings me to the page so and the second leads to the same page but with a javascript action activated.
I hope I have been clear enough and that this is possible, thank you for your response.
adding a class/id to it would help I think. I'm new here so let me know if that's what you are looking for
<a class="script" href="...">Link</a>
then in your javascript, you can manipulate it
var link = document.querySelector(".script");
link.addEventListener("click", function(){
// your function here
});
You can make this happen by sending url parameters with each href button: /page.html?action=1 . See parsing url parameters in javascript
Next on page.html use the following javascript:
window.onload = function() {
let url = new URL(window.location.href);
let action = url.searchParams.get("action");
if (action == "1") {
//perform an action
action1();
} else if (action == "2") {
action2();
}
};
Basically, I have a page where there are buttons that lead to another page or there are buttons that make things happen in js, and I want that when we click the button on the first page, we arrives on the second page when js is activated.
Basically I explain my site I have a button "visual identity" which should lead to another page (easy), on this second page there is
sub-buttons like "fish" which display a menu with js commands, its sub-buttons are also on the first page and I want when you click on the sub-button on the first page it will take you to the second page with menu opening.
I don't know if that's what you understood just above?
but thanks for your reply.

Define a reference site for the history.back button

We want to have a back button in our site
but history.back in javascript does not help us.
We need this function only run on the site and if the user comes from other site, clicking the return button on the previous site should not return.
In fact, we want a return button to run on our site only.
my code is
<i class="fas fa-arrow-left"></i><span class="btn-text">Back</span>
This only works for your own made back button and won't work with the browser back button
There is two ways to achieve that: a simple but not always reliable method and a complex one but always good.
1- The simple method
You use document.referrer and ensure the domain is yours before calling history.back().
2- The complex method
You could register a JavaScript function on page load to get the first URL the internaut land which you could store using history.pushState. Before calling the back function, you could ensure this is not that page. Though, this idea is not complete as the user could probably have landed on this page twice. i.e. Home->Product->Home. I'll let you search for further code that would let you counter this problem.
This code checks the history of back button of the browser on its click event:
$('#backbtn').click(function () {
if (document.referrer.includes(window.location.hostname)) {
window.history.back();
} else {
window.location.href = "/your/path";
}
});

How to track a user coming from a certain URL to trigger a function using JavaScript

I am wanting to trigger a function that will display all events but only when the user comes from a URL with /events/ in it.
Right now I am using referrer to take the user back to the page and to scroll to the last event they clicked on. But if the event they clicked on has to be loaded by clicking 'view more' it will just scroll to the bottom of the page. I need all the events to collapse when the user hits the return button.
Any help is much appreciated!
You can achieve what you're trying to do with localStorage:
if(!!localStorage.getItem("isEventsInPath")) {
// user came from /events
}
var isEventsInPath = document.location.pathname.includes("/events/");
localStorage.setItem("isEventsInPath", isEventsInPath);
// keep the order intact!
You can use the following to parse the URL and call your function:
$(document).ready(function(){
if(document.location.pathname.includes("/events"))
{
//CALL YOUR FUNCTION
}
});
This parses the path name and checks if /events exists in it.

How to keep the innerhtml content that is changed with the JS onclick function

this is a simple problem but cant seem to solve it.
I want to be able to change the innerhtml content of a link, once is triggered by an onclick function triggered from separate link that actually takes the user to another page (inside the website not external site), I get the script to work but the desirred innerhtml content to be changed dissapears once the page reloads and goes to the other page the link is pointing to. I actually want to keep the change of the text change even if the page is reloaded and taken elsewhere.
The script looks like something like this:
<script>
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
} //Js script that does the innerHMTL change
</script>
eng // button that triggers the onclick function but takes the user to another page inside the site
<a href="http://example.com" id="testchange" >Hello</a> // text to be changed by JS and want to keep the change even if the page is reloaded and taken elsewhere
So any ideas how i could do that? Thanx
For this to work you need some kind of storage. Let's try localStorage:
You first check if the changes has been made before setting the variable, then handle your event:
<script>
function ready(fn) {
if (document.readyState != 'loading'){
fn();
} else {
document.addEventListener('DOMContentLoaded', fn);
}
}
}
function myFunction() {
document.getElementById("testchange").innerHTML = "Get Started";
//this will save the state of the change
localStorage.setItem('textSet', true);
}
//this will change the text when the page is loaded if the change has been made before.
ready(function(){
if(localStorage.getItem('textSet')){
document.getElementById("testchange").innerHTML = "Get Started";
}
})
</script>
Either use Cookies or Session/Local storage, sessionStorage option below
Data stored in sessionStorage will lasts as long as the browser window is open, whereas localStorage has no expiration time
eng
<a href="http://example.com" id="testchange" >Hello</a>
<script>
function setFlag() {
sessionStorage.setItem('setFlag', 'true');
}
if (sessionStorage.getItem("setFlag"))
document.getElementById("testchange").innerHTML = "Get Started";
</script>
Note: this code will need to be place after your HTML elements ideally at bottom of the page

Display text when user clicks on any link

I want to display my licence agreement when the user clicks on any link on the page and prevent the link from taking the user anywhere. I need a way to make any click on the page show the code I want. Is there an easy way to do it? Like a scripts that tells the browser "when the user clicks something show this...".
Thanks a lot for any info
Plain javascript (but without any test for existing onclick handlers):
in the head add
<script>
var disclaimer="This link is not our responsibility - click ok to continue"
window.onload=function() {
var links = document.links;
for (var i=0, n=links.length;i<n;i++) {
links[i].onclick=function() { return confirm(disclaimer);}
}
}
</script>
Jquery:
$('a').click(function() {
// show whatever you want
});

Categories