Run function on active anchor - javascript

I'm new to jQuery and want to highlight div's if the div's anchor id is set.
I currently have this construct which only works on page load with an valid anchor attached.
$(document).ready(function(){
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
});
This works only on page load with a set anchor. How can I make this more dynamic so the script executes whenever the anchor changes?

jQuery can hook into the hashchange event so you can do this:
$(window).on('hashchange', function(e){
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
});

You can make it a function and call it with every update.
function updateAnchors() {
var divpost = window.location.hash.substr(1);
if($.isNumeric(divpost)){
$('#reply_' + divpost).css('background-color', '#EDA2FF');
}
}
Then call updateAnchors() when more anchors are loaded.

Related

jQuery doesn't let me use href

jquery:
$(".container").on("click", function(e) {
e.preventDefault();
var currentBox = $(this).siblings(".map").toggleClass("active");
$(".map.active").not(currentBox).removeClass("active");
});
html:
Because of this i cant use href anymore.
I use the jqueryto show more links.
It appears that you're trying to use div's and p's like anchors (a). href is not a valid attribute of div or p.
If you're trying to store data in the div and p tags, use data-href="" in conjunction with window.open()
Based on the limited code provided, my guess is that you're trying to do something like this:
$(".container").on("click", function(e) {
e.preventDefault();
const $this = $(this);
$(".map.active").removeClass("active");
$this.siblings(".map").toggleClass("active");
let href = $this.attr("data-href");
// Open a new window
window.open(href);
// OR
// Navigate without opening new window
window.location.href = href;
});
Or, you could skip the jQuery all together an just use anchor tags as they're designed to be used.
You can use jQuery for get any attribute of elements. So if you want to use href, just do:
var new_location = $('a').attr('href');
So you can do anything by click on a tag and at the least redirect to href path by:
window.location.href = $(this).attr('href');
Note: $(this) point to current clicked a tag. So you have something like this:
$(".container").on("click", function(e) {
e.preventDefault();
var currentBox = $(this).siblings(".map").toggleClass("active");
$(".map.active").not(currentBox).removeClass("active");
window.location.href = $(this).attr('href');
});

Jquery .replaceWith not working proper

i have a jquery code that is preventing a link to go to that link but executing it. The problem i have is that after it executs the script and script is returning data i want to replace it with a new one but with the same class. The replace is doing inside the dom but next time i press that link is not prevening going to that link but the class is the same, here is my code:
<script>
$(".recomanda").click(function(e){
e.preventDefault();
var test=$(this);
var href = $(this).attr('href');
$.getJSON(href, function(data) {
if(data.recom==1)
{
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomandat</a> ');
}
if(data.recom==0)
{
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda</a> ');
}
});
});
</script>
html
<a class="recomanda" href="app/recomanda_produs.php?id='.$row['ID_Produs'].'&recom=0">Recomanda</a>
yeah, I ran into that problem too before, it's because when you attach click to recomanda on ready(), but when ajax load, everything in ready() won't fire again, that why you need to attach the event to non-dynamic elements, and let it find it's child selector.
$('body').on('click', '.recomanda', function() {});
When you call a replaceWith actually you are removing elements that are bound to onclick handler:
.replaceWith()
Description: Replace each element in the set of matched elements with
the provided new content and return the set of elements that was
removed.
The main idea is that you handler must be bound to the same element (that is not removed when clicking).
So instead of using replaceWith method use method that modify existing element like this:
test.attr('href', blablabla);
And this is not a problem, but second time you don't need to use $ with test variable.
You need to delegate the event to a parent so that it can be applied to specific children wether they exist now or in the future.
See: http://learn.jquery.com/events/event-delegation/
$("body").on("click", ".recomanda", function(e){
e.preventDefault();
var test=$(this);
var href = $(this).attr('href');
$.getJSON(href, function(data) {
if(data.recom==1){
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda"+((data.recom==1)?"t":"")+"</a> ');
}
if(data.recom==0){
$(test).replaceWith('<a class="recomanda" href="app/recomanda_produs.php?id=' + data.id + '&recom=' + data.recom + '">Recomanda</a> ');
}
});
});

jQuery function works on click() not on ready()

I'm trying to change the 'href' attribute to match that of a sibling element.
$(function() {
$(".container").click(function() {
var href = $(this).find('.one').attr('href');w
$(this).find('.two').attr('href', href);
});
})
when the 'click();' event handler is used and I click on .container, the href of .two updates, however, when just using ready(); to execute it as soon as the page loads, it doesn't execute.
If you want to keep the context within .container element, just change click function to each, like this:
$(function() {
$(".container").each(function() {
var href = $(this).find('.one').attr('href');
$(this).find('.two').attr('href', href);
});
});
For more information about jQuery's each function, please refer here.
UPDATE
Also you can improve the performance a bit by caching the value of $(this), like this:
$(function() {
$(".container").each(function() {
var $this = $(this),
href = $this.find('.one').attr('href');
$this.find('.two').attr('href', href);
});
});
UPDATE 2
If you don't care about the context of .container, here is the code that will change href attributes of all those elements with class .two, which come after an element with class .one.
Here is the live example in JSFiddle.

Stoping a link from executing it's href path

Hi I am trying to stop a link from executing it's default action , but I seem to have no luck.Here is my code:
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
});
var lightbox = {
init : function(actionString){
$("<div id='lightbox-background'></div>").appendTo("body");
$("<div id='lightbox'></div>").appendTo("body");
$("<p></p>").appendTo("#lightbox");
$("<a href='#' id='ok'>OK</a>").appendTo("#lightbox");
$("<a href='#' id='cancel'>Cancel</a>").appendTo("#lightbox");
}
}
I hoped that if I used e.preventDefault it would stop the link from from going to it's href path but it did not work.Am I doing something wrong?
EDIT: I just noticed that if I remove the call for the lightbox object from the click event handler the e.preventDefault() works.
Your problem is in this line:
var lightbox = $("#lightbox");
in onclick callback function hide
variable name is the same as name of global lightbox object defined outside click callback. Local variable mentioned above simply override global variable inside that function scope. Basically, you are calling init of $("#lightbox"):
$("#lightbox").init("....")
Not sure what are you doing, but try to update your code like this:
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightboxElement = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
});
Besides, calling
var container = $("#lightbox-background");
var lightboxElement = $("#lightbox");
at the first time, you will get an empty set of elements as init method is not executed at that moment and elements you are looking for are not created yet.
Try if it works
$("a.delete").on("click", function (e) {
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
e.preventDefault();
return false;
});
Have you tried it above the vars declared:
$("a.delete").on("click", function (e) {
e.preventDefault();
var container = $("#lightbox-background");
var lightbox = $("#lightbox");
lightbox.init("Are you sure you want to delete this book?")
});
Just noticed that you have missed a ';' at closing here:
var lightbox = {
init : function(actionString){
$("<div id='lightbox-background'></div>").appendTo("body");
$("<div id='lightbox'></div>").appendTo("body");
$("<p></p>").appendTo("#lightbox");
$("<a href='#' id='ok'>OK</a>").appendTo("#lightbox");
$("<a href='#' id='cancel'>Cancel</a>").appendTo("#lightbox");
}
}; //<----this one
Example for a link like:
google
use javascript with jQuery
$("a").click(function(e){e.preventDefault(); return false;});
this will not redirect any link on the page :)
or in given case it will be like
$("a.delete").click(function(e){e.preventDefault(); return false;});
Note: Added e.preventDefault(); to prevent the event from triggering.

Jquery syntax and variables

I'm trying to make a FadeOut effect after clicking a link. But my syntax seems to be wrong. When i click, it fadeout, and go to a "~~nothing~~.html" page, it just dont get the value to compose the variable.
the id boo is attached to the tag (body id="boo") and in the css stylesheet the id #boo is set to display:none;
I'm using jquery-1.7.2.min
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(e) { //When something with the id 'go' is clicked,
e.preventDefault(); //Prevent default action (?)
var url = $('#go').val() + ".html"; //set url as "Clicked 'go' value + .html" (374.html"
$('#boo').fadeOut(600, function() { window.location.href = url; }); //fadeOut what is with the 'boo' id (body), and load the created address as a new page (?)
});
});
</script>
<a id="go" value="374" href="#">Go to page 374</a>
the 374.html page is in the same folder. If possible, please explain what have i done wrong, and make it step by step. I'm new to jquery.
Thank you!
the .val() method only applies to fields, just putting a value attribute on any element will not be read with the val() method.
Instead use .attr('value').
Or, its better practice to use data-* attributes and use the data() method:
<script type="text/javascript">
$(document).ready(function(){
$('#go').click(function(e) { //When something with the id 'go' is clicked,
e.preventDefault(); //Prevent default action (?)
var url = $('#go').data('value') + ".html"; //set url as "Clicked 'go' value + .html" (374.html"
$('#boo').fadeOut(600, function() { window.location.href = url; }); //fadeOut what is with the 'boo' id (body), and load the created address as a new page (?)
});
});
</script>
<a id="go" data-value="374" href="#">Go to page 374</a>
The val() function won't give you that value from an anchor tag, use attr("value") to get the valuue of the a tag
$(document).ready(function(){
$('#go').click(function(e) {
e.preventDefault();
var url = $('#go').attr("value") + ".html";
alert(url)
$('#boo').fadeOut(600, function() {
window.location.href = url;
});
});
});​
Alternatively, you can use HTML 5 data attribute to store such kind of value
<a id="go" data-someValue="374" href="#">Go to page 374</a>
And you can access it in javascript like
var someVal=$("#go").data("someValue");
sample http://jsfiddle.net/LyPZB/1/
The a tag doesn't support the attribute value, you should do like this:
set the anchor like this
<a id="go" data-page="374" href="#">...
(data-xxx are custom attributes)
and get its value with
$('#go').data('page')
In this way it will work and you will respect the HTML standard (since the anchor shouldn't have the value attribute)
Try:
var url = $('#go').attr("value") + ".html";
instead of
var url = $('#go').val() + ".html";
From the jQuery docs -
The .val() method is primarily used to get the values of form elements
such as input, select and textarea. In the case of elements, the .val() method returns an array
containing each selected option; if no option is selected, it returns
null.
There's an example here - http://jsfiddle.net/A8ArH/

Categories

Resources