I'm trying to set up a website that loads pages through ajax calls replacing the current contents of with the ajax response. I'm putting a # and a page name at the end of my URLs so that people can book mark pages.
www.examplesite.com#home
www.examplesite.com#examples
www.examplesite.com#examples/example1
www.examplesite.com#examples/example2
I'm new to jQuery and to a lesser extent JavaScript but I'm trying to get a different page animation when I go to a page that is stored in a sub folder. fadeIn() works fine on both pages and pages in sub-folders however I can't get .slideDown() or .animate() to work at all. Here is an extract from my code:
<script>
//All pages are stored in a folder called 'pages' or a subfolder of 'pages'
$(document).ready(function(){
var myUrl = $(location).attr('href');
var noPage = myUrl.indexOf('#');
if(noPage == -1) {
location.hash = 'home';
}
window.onhashchange = function() {
pageChange();
}
function pageChange() {
var myUrl = $(location).attr('href');
var page = myUrl.substring(myUrl.indexOf('#') + 1, myUrl.length);
$.get('pages/' + page + '.html', function(pageHtml) {
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).slideDown(400);
} else {
$('.main').hide().html(pageHtml).fadeIn(400);
}
});
};
pageChange();
});
</script>
If I'm approaching this from completely the wrong direction and that's why it's not working do feel free to point me in the correct direction by giving me an example of how it should work.
Got it!
I was using the css min-height property with a couple of my divs so that the page would expand automatically with the content if there was a lot on the page. If I remove the min-height property and replace it with a fixed height .slideDown() works fine.
Here are some links for more info if anyone else has the same issue:
http://www.only10types.com/2011/09/jquery-slidedown-doesnt-work-on.html
http://docs.jquery.com/Tutorials:Getting_Around_The_Minimum_Height_Glitch
I would take this...
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).slideDown(400);
} else {
$('.main').hide().html(pageHtml).fadeIn(400);
}
And rearrange it to make sure your if statement is correct
if (page.indexOf('/') != -1) {
$('.main').hide().html(pageHtml).fadeIn(400);
} else {
$('.main').hide().html(pageHtml).slideDown(400);
}
If it now slides instead of fades, the if statement is corrupt
What about this ? Does this work ?
var main_div=$('.main');
main_div.hide();
$.get('pages/' + page + '.html', function(pageHtml) {
if (page.indexOf('/') != -1) {
main_div.html(pageHtml)
} else {
main_div.html(pageHtml)
}
});
main_div.slideDown(400);
maybe something in the CSS must be blocking it ? try disabling the CSS for the main class and try again ?
Related
I am running this code in Chrome console dev tools and it works:
const params = new URLSearchParams(window.location.search);
if (window.location.href.indexOf("Phone") != -1) {
$('.test111232 a').attr('href', 'tel:1 ' + params.get('Phone'));
}
if (window.location.href.indexOf("state") != -1) {
$('.test111232234 a').attr('href', 'https://www.example.com/ddd?state=' + params.get('state'));
}
However, when I save the page on WordPress with the Elementor HTML widget, it only changes the first number on the page.
Any ideas?
ok so basically what fixed the error was to add this:
$(document).ready(function()
before the code above, so it looks like this:
<script>
$(document).ready(function() {
const params = new URLSearchParams(window.location.search);
if (window.location.href.indexOf("Phone") != -1) {
$('.test111232 a').attr('href', 'tel:1 ' + params.get('Phone'));
}
if (window.location.href.indexOf("state") != -1) {
$('.test111232234 a').attr('href', 'https://www.example.com/ddd?state=' + params.get('state'));
}
});
</script>
one side point that might be relevant. I had an older version of elementor pro which could be impacting js loading through the html widget.
I had the script opening and closing tags but for some reason it wanted the function and then it worked. Could be that's the way it's suppose to be in the first place.
I have some javascript which looks at the body and finds words and if one is present, it outputs a div. This is useful for many things, however...
What I need to do is also look at the body and all the ALT tags for the page as well.
I found this: Use javascript to hide element based on ALT TAG only?
Which seems to change the ALT attribute, however I want to perform an action.
Here's my JS so far.
var bodytext = $('body').text();
if(bodytext.toLowerCase().indexOf('one' || 'two')==-1)
return;
var elem = $("<div>Text Here</div>");
Thank you.
P.S. I am a N00B/ relatively new at JS, I am doing this for a small project, so I am not sure where to start for this in terms of JS functions.
Updated Answer
Try this out, I commented the code to explain it a bit.
// build array of triggers
var triggers = ['trigger1','trigger2','trigger3'];
// wait for page to load
$(function() {
// show loading overlay
$('body').append('<div id="mypluginname-overlay" style="height:100%;width:100%;background-color:#FFF;"></div>');
// check page title
var $title = $('head title');
for(trigger of triggers) {
if($($title).innerHTML.toLowerCase().indexOf(trigger) >= 0) {
$($title).innerHTML = '*censored*';
}
}
// check all meta
$('meta').each(function() {
var $meta = $(this);
for(trigger of triggers) {
if($($meta).attr('name').toLowerCase().indexOf(trigger) >= 0) {
censorPage();
return; //stop script if entire page must be censored
} else if($($meta).attr('content').toLowerCase().indexOf(trigger) >= 0) {
censorPage();
return; //stop script if entire page must be censored
}
}
});
// check all img
$('img').each(function() {
var $img = $(this);
for(trigger of triggers) {
if($($img).attr('alt').toLowerCase().indexOf(trigger) >= 0) {
censor($img);
}
}
});
// check all video
$('video').each(function() {
var $video = $(this);
for(trigger of triggers) {
if($($video).attr('alt').toLowerCase().indexOf(trigger) >= 0) {
censor($video);
}
}
});
// if you want to be extra careful and check things like background image name,
// you'll have to run this code here - very inefficent
// but necessary if you want to check every single element's background image name:
for($element of $('body').children()) {
for(trigger of triggers) {
if($($element).css('background-image').toLowerCase().indexOf(trigger) >= 0) {
$($element).css('background-image','');
}
}
}
, function() { // Not sure if this is totally correct syntax, but use a callback function to determine when
// when the rest of the script has finished running
// hide overlay
$('#mypluginname-overlay').fadeOut(500);
}});
function censor($element) {
// just a basic example, you'll probably want to make this more complex to overlay it properly
$element.innerHTML = 'new content';
}
function censorPage() {
// just a basic example, you'll probably want to make this more complex to overlay it properly
$('body').innerHTML = 'new content';
}
---Original Answer---
I'm not sure exactly what you would like to do here, you should add more detail. However if you choose to use jQuery, it provides tons of useful methods including the method .attr(), which lets you get the value of any attribute of any element.
Example:
var alt = $('#my-selector').attr('alt');
if (alt == 'whatYouWant') {
alert('yay');
} else {
alert('nay');
}
You're using jQuery lib, you could select elements by attribute like:
$('[alt="one"]').each(function(el){
// do something
var x = $(el).arrt('alt');
});
If you use selector $('[alt]') you can get elements that have this attribute set, and then check the value of the element if you have a more complicated selection.
Than you have to change your return, as you could not put a div inside an ALT tag, it didn't work.
Here is about what is your expected output.
UPDATE
As you want to change all images and video in a page, the way to do this with jquery is through $.replaceWith():
$('img,video').replaceWith($('<div>Text Here</div>'));
If you need to filter the elements:
$('img,video').each(function(el){
if($(el).prop('tagName') == 'IMG' &&
$(el).attr('alt') == 'the text...') {
$(el).replaceWith($('<div>Text Here</div>'));
}
})
But I'm not an expert on Chrome Extensions, I just put this code here in jQuery, as you was using jQuery.
Of course it could be done, with much code with plain javascript and the DOM API.
I am new at AJAX and JQuery and trying to use them in the part of my website. Basically the website that I have, has this kind of design and currently it is functional (Sorry for my poor paint work :)
The items in the website are created by user. This means item number is not constant but can be fetched by db query.
Each item has a unique URL and currently when you click an item, all page is refreshing. I want to change the system to let the user have a chance to navigate quickly between these items by only chaning middle content area as shown above. However I also want to have a unique URL to each item. I mean if the item has a name like "stack overflow", I want the item to have a URL kind of dev.com/#stack-overflow or similar.
I don't mind about the "#" that may come from AJAX.
In similar topics I have seen people hold constant names for items. For instance
<a href="#ajax"> but my items are not constant.
WHAT I HAVE TRIED
Whats my idea is; while fetching all item's links, I'm holding links in $link variable and using it in <a href="#<?php echo $link; ?>">.
Inside $link it is not actual URL. it is for instance a name like "stack-overflow" as I ve given example above. Until this part there is no problem.
PROBLEM
In this topic a friend suggested this kind of code as an idea and I ve changed it for my purpose.
<script>
$(document).ready(function() {
var router = {
"<?php echo $link ?> ": "http://localhost/ajax_tut/link_process.php"
};
$(window).on("hashchange", function() {
var route = router[location.hash];
if (route === undefined) {
return;
} else {
$(".content-right").load("" + route + " #ortadaki_baslik");
}
});
});
</script>
I'm trying to post the value of $link to the link_process.php and at link_process.php I will get the value of $link and arrange neccessary page content to show.
The questions are;
- How should I change this code to do that?
- I couldnt see someone doing similar to take as an example solve this
issue. Is this the right way to solve this situation?
- Do you guys have a better solution or suggestion for my case?
Thanks in advance.
WHEN your server side AJAX call handler [PHP script - handling AJAX requests at server side] is constant and you are passing item_id/link as GET parameter...
For example:
localhost/ajax_tut/link_process.php?item_id=stack-overflow OR
localhost/ajax_tut/link_process.php?item_id=stack-exchange
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/link_process.php?item_id=";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route );
}
});
});
</script>
WHEN you are passing item_id/link as URL part and not parameter...
For example:
localhost/ajax_tut/stack-overflow.php OR
localhost/ajax_tut/stack-exchange.php
Then you can use following code.
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/";
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
$(".content-right").load( ajax_handler + route + ".php");
}
});
});
</script>
WHEN Your server side AJAX handler script url is not constant and varies for different items...
For example: localhost/ajax_tut/link_process.php?item_id=stack-overflow OR localhost/ajax_tut/fetch_item.php?item_id=stack-exchange OR localhost/ajax_tut/stack-exchange.php
Then I suggest to change PHP script which is generating item's links placed on left hand side.
<?php
foreach($links as $link){
// Make sure that you are populating route parameter correctly
echo '<a href="'.$link['item_id'].'" route="'.$link['full_ajax_handler_route_url_path'].'" >'.$link['title'].'</a>';
}
?>
Here is Javascript
<script>
$(document).ready(function() {
var ajax_handler = "localhost/ajax_tut/"; //Base url or path
$(window).on("hashchange", function() {
var route = location.hash;
if (route === undefined) {
return;
} else {
route = route.slice(1); //Removing hash character
route = $('a [href="'+.slice(1)+'"]').attr('route'); //Fetching ajax URL
$(".content-right").load( ajax_handler + route ); //Here you need to design your url based on need
}
});
});
</script>
So,
I'm trying to come up with a way to dynamically load content into multiple tabs, where each tab can contain anywhere from one to several elements (reports).
Currently, the reports are loaded on page load with jQuery $.load. I'm using Bootstrap and bootstrap tabs. I found a site that teaches how to load multiple tabs, but not specifically what I need to do. That site is here: http://www.mightywebdeveloper.com/coding/bootstrap-2-tabs-jquery-load-content/
In contrast, each tab is set up more like this:
<div id="tab1">
<div id="report1"></div>
<div id="report2"></div>
</div>
I cannot use the top-level div to load the content, because it will potentially have multiple children. I need to loop through the div's, use regex to parse the ID, and load each report when the tabs are changed.
I haven't yet figured out the regex expression, but it should be fairly simple - the element id will be something like this : "#be78f5aa3-25". This is an alphanumeric 9-character dbid, followed by a hypen, followed by a 1-3 digit integer (not starting in 0). Then I need to split those two strings into separate variables and inject them into an API call.
Anyone looking to load multiple pages into bootstrap tabs may find this of use. I was able to get it working using some regex (specific to my application), placing div's within the tab-pane container's that had an Element Id which could be used to create the report I wanted to load into the container using $.load. I also added a few things for persistent tabs when the user went to another page and then used the back button, and another condition to load the content in the first tab if there was no hash in the URL.
I'm sure it could be cleaned up, but you get the gist..
$(function() {
"use strict";
var baseURL, $navbox;
baseURL = window.location.protocol + "//" + window.location.hostname + "/db/";
$navbox = $("#myTabs");
$navbox.bind("show", function(e) {
var contentID, pattern, selectDiv;
pattern = /#(\Btab|tab\B)?(\Bdropdown|dropdown\B)?([1-9]{1}[0-9]*)/i;
contentID = e.target.toString().match(pattern)[0];
selectDiv = contentID + " > div";
return $(selectDiv).each(function() {
var parts = this.id.match(/(##enter regex here)/);
if (parts) {
$(this).load(baseURL + parts[0]);
return;
}
return $("#myTabs").tab();
});
});
if (window.location.hash) {
$('#myTabs').find('a[href="'+window.location.hash+'"]').tab('show');
}
else {
var elemID = "#"+$('[class^="tab-pane active"]').attr('id') + " > div";
$(elemID).each(function() {
var parts = this.id.match(/(##enter regex here)/);
$(this).load(baseURL + parts[0]);
return $("#myTabs").tab();
});
}
});
$('#myTabs a').click(function (e) {
e.preventDefault();
var bob = jQuery(this).attr("href");
bob = jQuery.trim(bob);
if(bob == "" || bob == "javascript:void(0)") {
return;
}
else {
window.location.hash = $(this).attr('href');
$(this).tab('show');
}
});
I was just wondering if there are any methods of creating nice, smooth transition effects when navigating between pages? Things like blind effects, sliding effects, etc. I guess I'm looking for something like what jQuery can do with images - but for actual web pages. I know there are fade effects and all that, but I was just wondering if there was something more 'modern' out there. While I realize Flash would be a good fit for this, it is not an option.
You can do some pretty cool effects if you use jQuery UI. They will go much smoother if you load everything in using AJAX... but, here's an example to get it working with full page loads.
First you need to additionally include jQuery UI (I just built my own and only grabbed the effects I needed):
<script type="text/javascript" src="jquery-ui-1.7.1.custom.min.js"></script>
And here's the javascript you'll need to make it work.
$(function() {
$('body').hide();
$('a').bind('click', function() {
var newPage = $(this).attr('href');
$('body').hide('blind',{},500, function() {
newPageParts = newPage.split('?');
newPageURL = newPageParts[0];
newPageParams = newPageParts[1];
newPage = newPageURL+"?transition=true"+(newPageParams != undefined ? "&"+newPageParams : '');
window.location=newPage;
});
return false;
});
if(getURLParam('transition') != '') {
$('body').show('blind',{},500,null);
}
});
function getURLParam(strParamName){
var strReturn = "";
var strHref = window.location.href;
if ( strHref.indexOf("?") > -1 ){
var strQueryString = strHref.substr(strHref.indexOf("?")).toLowerCase();
var aQueryString = strQueryString.split("&");
for ( var iParam = 0; iParam < aQueryString.length; iParam++ ){
if (aQueryString[iParam].indexOf(strParamName + "=") > -1 ){
var aParam = aQueryString[iParam].split("=");
strReturn = aParam[1];
break;
}
}
}
return strReturn;
}
Of course, fading in is only going to work on pages that have this script on it...
Just a note: I did just kinda make this in a few minutes so it might be really ghetto. But, it does work... so... yeah...
IE has a very simple implementation of page transition effects, but I don't think they will work on other browsers like Mozilla and Safari.